Home > Software design >  How to print print every element in array in loop if with diffrent types of element
How to print print every element in array in loop if with diffrent types of element

Time:05-24

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 phone.showDetails() method from phones array, but i cant find a way to do it. there`s a problem with data type conversion or sth. i want to achive 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