Home > Back-end >  How to print every element in array in loop if with different types of element?
How to print every element in array in loop if with different types of element?

Time:05-25

I have this phone class:

   public class Phone {
        private int id;
        private String brand;
        private String model;
        private int cameraResolution;
        
    public Phone(int id, String brand, String model, int cameraResolution) {
        this.id=id;
        this.brand=brand;
        this.model=model;
        this.cameraResolution= cameraResolution;
    }
    
        public void showDetails() {
            System.out.println("id "  this.id);
            System.out.println("Marka to "  this.brand);
            System.out.println("Model to "  this.model);
            System.out.println("Rozdzielczosc aparatu to "   this.cameraResolution);    
        }
    
and this main class

import java.util.ArrayList;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        Phone galaxy= new Phone(1, "Samsung","Galaxy",12);
        Phone lumia= new Phone(2, "Nokia","Lumia",13);
        Phone pixel= new Phone(3, "Google","Pixel",14);
        
    galaxy.showDetails();
    
    //String[] phones = new String[3];
        //phones[0]="galaxy";
        //phones[1]="lumia";
        //phones[2]="pixel";
    
    Phone[] phones = new Phone[3];  
    phones[0]= galaxy;
    phones[1]= lumia;
    phones[2]= pixel;
    
    // dont work System.out.println(Arrays.oString(phones));
    
    }
}

I want to write a loop, that will call the phone.showDetails() method from the phone's array, but I can't find a way to do it. There's a problem with data type conversion or sth.

I want to achieve a loop, that will call: galaxy.showDetails, then lumia.showDetails() and pixel.showDetails();

CodePudding user response:

You can loop through every element and print its details.

for (Phone phone: phones){
    phone.showDetails();
}

CodePudding user response:

Your big issue is your phone class doesn't override toString(), so all youre going to see is memory address space. Do something like this:

@Override
public String toString() {
    return "Phone [id="   id   ", brand="   brand   ", model="   model   ", cameraResolution="
                  cameraResolution   "]";
}

As for looping through, there are lots of ways you can do this, but the easiest:

for (Phone phone : phones) {
    System.out.println(phone);
}
  • Related