方法onOffSwitch()& checkSwitch()打开/关闭电视

时间:2014-04-27 07:05:29

标签: java

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

课堂电视

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 ());
}} 

2 个答案:

答案 0 :(得分:1)

您需要在检查方法中使用if(flag)if(flag==true)代替if(flag=true)

if(flag=true)true分配给flag并返回true,导致true分支始终执行

答案 1 :(得分:0)

使用您的checkSwitch()方法

if (flag=true)

这是赋值而不是比较,即=是赋值运算符,而==是比较运算。所以当你说

if (flag=true)
每次都将

标志设置为true。每次您的电视始终开启时,此任务都是正确的。将其更改为

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

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