gpt4 book ai didi

java - 打开/关闭电视的 onOffSwitch() 和 checkSwitch() 方法

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

我无法关闭电视并检查开关状态。我有什么做错的地方吗?

类电视

public class TV{

// instance variables
private int channel;
private boolean flag;
private boolean check;
// constructor
public TV()
{
//default value
channel = 1;
volume = 0;
flag = false;
}

// accessor
//The method setChannel(int channel) that sets the channel.
public void setChannel(int channel) {this.channel = channel;}

//The method viewChannel() that displays the channel.
public int viewChannel() {return channel;}



//methods

//The method onOffSwitch() that turns the TV on/off.
public void onOffSwitch()
{

flag = !flag;

}

//checkSwitch()方法,无论电视是打开还是关闭,都会显示一条消息。

public String checkSwitch(){
String TVState = "";

if (flag=true)
return "TV is on";
else
return "TV is off";
}

//to String

public String toString ()
{
return "Channel: " + viewChannel() + "\nVolume: " + viewVolume() +"\nTVState: " + checkSwitch() + "\nFlag :" + flag + "\nCheck :"+ check;}
}

TVAPP

公开课TVApp{

public static void main(String args[]){
TV t1 = new TV();

t1.setChannel (2);

t1.onOffSwitch();//on
System.out.println (t1.toString ());
System.out.println ("");

TV t2 = new TV();

t2.setChannel (3);

t2.onOffSwitch();// on
t2.onOffSwitch();//off
System.out.println (t2.toString ());
}}

最佳答案

您需要使用 if(flag)if(flag==true) 而不是 if(flag=true)您的检查方法

if(flag=true)true 分配给 flag 并返回 true,从而产生 true 分支始终执行

关于java - 打开/关闭电视的 onOffSwitch() 和 checkSwitch() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23320427/

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