gpt4 book ai didi

java 对于存储的每个对象引用,调用对象方法

转载 作者:行者123 更新时间:2023-12-01 10:25:01 24 4
gpt4 key购买 nike

我需要一些帮助。我想打印电话对象以及每个电话对象特定的方法。我创建了一个列表,对于每个循环,我还有一个 toString() 方法,它打印下面的输出 我想要做的是在特定电话对象名称: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
);
}

最佳答案

what I want to do is call a method streamVideo on a specific phone object Name: G200 using 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
);
}

关于java 对于存储的每个对象引用,调用对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35394068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com