[英]How to print every element in array in loop if with different types of element?
我有这个电话课程:
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));
}
}
我想写一个循环,它会从电话的数组中调用 phone.showDetails() 方法,但我找不到办法。 数据类型转换或某事有问题。
我想实现一个循环,它将调用:galaxy.showDetails,然后是 lumia.showDetails() 和 pixel.showDetails();
您可以遍历每个元素并打印其详细信息。
for (Phone phone: phones){
phone.showDetails();
}
您的大问题是您的电话类不会覆盖toString()
,因此您将看到的只是内存地址空间。 做这样的事情:
@Override
public String toString() {
return "Phone [id=" + id + ", brand=" + brand + ", model=" + model + ", cameraResolution="
+ cameraResolution + "]";
}
至于循环,有很多方法可以做到这一点,但最简单的方法是:
for (Phone phone : phones) {
System.out.println(phone);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.