我有一些代码和我在我的班上的章节,在那里我学习作文。 我想这对你们来说是很容易解决的,但是现在我很难解决这个问题。 它是关于测试src中的代码,我试图将对象放在一起并显示对象的字段。 我的System.out.println(tv.GetResolution()); 正在给我“section7.resolution@1DB9742”,而我正试图获取200,100 int值来显示。。。 有人能帮我吗?我已经在这上面困了两个小时了,在网上什么都找不到。 试图更改返回类型等x.x
public class TV {
private String model;
private Resolution resolution;
public TV(String model, Resolution resolution) {
this.model = model;
this.resolution = resolution;
}
public String getModel() {
return model;
}
public Resolution getResolution() {
return resolution;
}}
“
public class Room {
private TV tv;
private Bed bed;
private Desk desk;
public Room(TV tv, Bed bed, Desk desk) {
this.tv = tv;
this.bed = bed;
this.desk = desk;
}
public void turnLightsON() {
roomLighting();
}
private void roomLighting() {
desk.lamp();
}
public void getResolution() {
this.tv.getResolution();
}
}
/
public class Resolution {
private int width;
private int height;
public Resolution(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}}
/
public class Test {
public static void main(String[] args) {
Bed bed = new Bed(100, 250, "LaBed");
Desk desk = new Desk(110,175,"Black");
Resolution resolution = new Resolution(200,100);
TV tv = new TV("Samsung", resolution);
Room room = new Room(tv,bed,desk);
room.turnLightsON();
System.out.println(tv.getResolution());
System.out.println(tv.getModel()); }}
您应该重写Resolution类中的toString()方法。
你可以在这里查阅资料:-
请看这里
resolution
是一个对象,而不是基元类型,因此当您尝试打印它时,您将使用默认的toString()
方法,该方法返回类名和哈希代码。 重写toString()
方法:
public class Resolution {
// your code here
public String toString() {
return String.valueOf(width) + "x" + String.valueOf(height);
}
}
或者这样做:
System.out.println(tv.getResolution().getWidth());
System.out.println(tv.getResolution().getHeight());