0

嘿伙计们,我刚刚创建了这个程序及其应用程序。该应用程序应该从原始类调用 toString 方法。一切都编译了,但是当我去运行应用程序时,什么都没有出现。有小费吗?这里是电视课

公共课电视{

private int channel;
private int volume;
private boolean power;
private String[] channelName = {"CBS", "FOX", "DISCOVERY", "PBS", "HBO", "CNN", "DISNEY", "CNN", "TBS", "USA"};



//No argument constructor
public Television()
{
    channel = 1;
    volume = 0;
    power = false;

}


public void powerChange()
{
    this.power = !this.power;
}

public void setVolume(int vol)
{
    if (vol>10)
    {
    volume = 10;
    }else
    {
        volume = vol;
    }
    if (vol<0)
    {
    volume = 0;
    }

}

public void increaseVolume()
{
    volume++;
}

public void decreaseVolume()
{
    volume--;
}

public int getVolume()
{
    return volume;
}

public void setChannel(int ch)
{
    if(ch>10)
    {
    channel = 10;
    }else
    {
        channel = ch;
    }
    if(ch<1)
    {
    channel = 1;
    }
}

public void increaseChannel()
{
    channel++;
}

public void decreaseChannel()
{
    channel--;
}

public int getChannel()
{
    return channel;
}

public String getChannelName(int channel)
{

    if (channel==1)
    {
        return channelName[0];
    }
    else if (channel == 2)
    {
        return channelName[1];
    }   
    else if (channel == 3)
    {
        return channelName[2];
    }   
    else if (channel == 4)
    {
        return channelName[3];
    }   
    else if (channel == 5)
    {
        return channelName[4];
    }   
    else if (channel == 6)
    {
        return channelName[5];
    }   
    else if (channel == 7)
    {
        return channelName[6];
    }
    else if (channel == 8)
    {
        return channelName[7];
    }   
    else if (channel == 9)
    {
        return channelName[8];
    }   
    else 
    {
        return channelName[9];
    }   


}


public String toString()
{
    if(!power)
    {
        return String.format("%s :%s\n%s :%d\n %s :%s\n%s :%d", "TV State", "OFF", "Channel No", channel, "Channel Name", getChannelName(channel), "Volume", volume);
    }
    else
    {
        return String.format("%s :%s\n%s :%d\n %s :%s\n%s :%d", "TV State", "ON", "Channel No", channel, "Channel Name", getChannelName(channel), "Volume", volume);
    }


}

}

这是应用程序

//Television App

公共类TelevisionApp {

public static void main (String[] args)
{
    //Creating Objects of class Television
    Television tv1 = new Television();
    //Television tv2 = new Television(5,5,false);

    //Invoking set methods
    tv1.powerChange();
    tv1.setVolume(3);
    tv1.setChannel(4);

    //Display first TV
    tv1.toString();

    //Display second TV
//  tv2.toString();



}

}

4

2 回答 2

3

您需要将字符串输出到控制台。利用System.out.println(tv1);

于 2013-11-12T04:21:43.853 回答
0

您只需显式调用 toString 方法,它会返回您格式化的字符串值,但您不会调用 println 方法在控制台上打印字符串值。

如果您想查看内容,您可以执行以下操作

System.out.println(tv1);

或者

System.out.println(tv1.toString());
于 2013-11-12T04:24:19.710 回答