我需要一些帮助。 我想打印手机对象和每个手机对象特有的方法。我创建了一个List,每个循环我也有一个toString()方法打印下面的输出我要做的是在特定的手机对象上调用方法streamVideo名称:G200使用toString( )。
public void streamVideo() {
System.out.println("Streaming");
}
输出
Name: LandLine 2000
No of pixels: 400
Width: 5.6
Height: 8.5
Weight: 80.5
Powered On: true
Recharging: false
Streaming: Streaming at index:0 **// wrong**
Name: G200
No of pixels: 510
Width: 4.5
Height: 8.6
Weight: 80.5
Powered On: true
Recharging: false
Streaming: Streaming at index:1 **// what I want**
List<Phone> phones = new ArrayList<>();
Phone landLine2000 = new Phone("LandLine 2000",400,5.6f,8.5f,80.5f,true,false);
Phone g200 = new Phone("G200",510,4.5f,8.6f,80.5f,true,false);
phones.add(landLine2000);
phones.add(g200);
int index = 0;
for (Phone phone : phones)
{
System.out.println(phone + " at index:" + (index++));
}
System.out.println();
@Override
public String toString()
{
return ("\n Name: " + getName() +
"\n No of pixels: " + getNoOfDisplayPixels() +
"\n Width: " + getWidth() +
"\n Height: " + getHeight() +
"\n Weight: " + getWeight() +
"\n Powered On: " + getIsPoweredOn() +
"\n Recharging: " + getIsRecharging() +
"\n Streaming: " + getStreamVideo() // Don't want to use get
);
}
答案 0 :(得分:1)
我想要做的是在特定手机上调用方法streamVideo 对象名称:G200使用toString()。
@Override
public String toString()
{
String str = "not Streaming";
//check whether the name is G200 or not.
if(getName().equals("G200"))
str="Streaming";
return ("\n Name: " + getName() +
"\n No of pixels: " + getNoOfDisplayPixels() +
"\n Width: " + getWidth() +
"\n Height: " + getHeight() +
"\n Weight: " + getWeight() +
"\n Powered On: " + getIsPoweredOn() +
"\n Recharging: " + getIsRecharging() +
"\n Streaming: " +str // Don't want to use get
);
}