gpt4 book ai didi

java - 我如何更改它以使用我的电视类(class)?

转载 作者:行者123 更新时间:2023-12-02 06:42:49 25 4
gpt4 key购买 nike

Create a Television store that can hold three Television objects in an array. Use the Television class below:

   class Television
{
boolean isOn;
} // end class Television

Use a for loop to print the isOn instance variable for each Television in the TelevisionStore. Use a second for loop to change the isOn instance variable for each Television to “true”. Finally, use a third for loop to print the isOn instance variable for each Television in the TelevisionStore array.

所以我创建了一个具有正确输出的程序:

public class TelevisionDriver
{
public static void main( String[] args )
{
boolean isOn[] = new boolean[3];
isOn[0] = false;
isOn[1] = false;
isOn[2] = false;

System.out.println( "Opening the tv store for the day... tv status:" +
"\n" );

for( int x = 0; x < 3; x++ )
{
System.out.println( "Television" + x + " on? " + isOn[x] );
}

System.out.println( "\n" + "Turning the tv's on..." + "\n" );

for( int y = 0; y < 3; y++ )
{
isOn[0] = true;
isOn[1] = true;
isOn[2] = true;

System.out.println( "Television" + y + " on? " + isOn[y] );
}
}
}

这被认为是正确的吗?我意识到该程序无法访问电视类,并且不知道如何更改它。

最佳答案

您需要构造电视对象:

Television tvs[] = new Television[3];
for (int i = 0; i < 3; i++) {
tvs[i] = new Television();
tvs[i].isOn = false;
}

然后访问它们是否打开就变成这样:

for (int x = 0; x < 3; x++) {
System.out.println("Television" + x + " on? " + tvs[x].isOn);
}

确实应该封装 isOn 变量,并且 Television 类应该有一个构造函数,但我不确定您是否已经学会了。

关于java - 我如何更改它以使用我的电视类(class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18970322/

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