1

我正在做一个 UML,但我不太确定如何执行我应该这样做的这些 mutator 方法:

+turnOn(): void       //sets on to true
+turnOff(): void      //sets on to false
+channelUp(): void    //increases channel by 1 if on, rolls to 1 after maximum
+channelDown(): void  //decreases channel by 1 if on, rolls to maximum after 1
+volumeUp(): void     //increases the volume by 1 if on and less than maximum
+volumeDown(): void   //decreases volume by 1 if on and greater than 0
+toString( ): String  //returns the current state(instance variable values)

我现在的代码:(请记住,mutator 部分是不正确的)

public class TV {
    private int volume;
    private int channel;
    private boolean on;
    private int maxVolume;
    private int maxChannel;

    TV() {
        volume = 1;
        channel = 1;
        on = false;
        maxVolume = 1;
        maxChannel = 1;
    }
    public int getChannel() {
        return channel;
    }

    public int getVolume() {
        return volume;
    }

    public boolean isOn() {
        return on;
    }

    public int getMaxChannel() {
        return maxChannel;
    }

    public int getMaxVolume() {
        return maxVolume;
    }
    public void setChannel(int i) {
        if (isOn() && i >= 1 && i <= maxChannel) channel = i;
    }

    public void setVolume(int i) {

        if (isOn() && i >= 0 && i <= maxVolume) volume = i;
    }

    public void setMaxChannel(int i) {
        maxChannel = i;
    }

    public void setMaxVolume(int i) {
        maxVolume = i;
    }

    // + turnOn() * * This is where the mutator methods begin I need help here * *

    // if (channel == maxChannel) channel = 1;
    // else channel++;

    //if (channel == 1) channel = max;
    //else channel--;

    // if (volume == maxVolume) volume = 1;
    // else channel++;
    //if (volume == 1) volume = max;
    // else channel--;

    public string toString() {
        return "channel: " + channel + "\nvolume: " + volume +
            "\non: " + on + "\nmax Channel: " + maxChannel +
            "\nmax Volume: " + maxVolume;
    }
}
4

3 回答 3

2

Mutator 通常与“setter”的含义相同

因此,在您上面的代码中,“getter”将是:

public int getMaxChannel() {
  return maxChannel;
}

'mutator' 或 'setter' 将是:

public void setMaxChannel(int maxChannel) {
  this.maxChannel = maxChannel;
}
于 2013-10-15T22:48:51.213 回答
0

我们可以互换使用 setter 和 mutator。

mutator 方法用于设置私有字段的值。它遵循一个命名方案,在方法名称的开头加上“set”这个词。这些方法没有返回类型,并且接受与其对应的私有字段具有相同数据类型的参数。然后使用该参数设置该私有字段的值。

下面是一些 mutators 或 setter 的例子:

public void setMaxChannel(int i) {
        maxChannel = i;
    }

public void setChannel(int c) {
        channel=c;
    }
于 2013-10-15T22:53:23.060 回答
0

样品方法:

public void turnOn() {
   this.on = true;
}

public void channelUp() {
   if (on) {
      if (channel == maxChannel) {
         channel = 1;
      }
      else {
         channel++;
      }
   }
}

public void volumeDown() {
   if (on && volume > 0) {
      volume--;
   }
}

其他方法遵循相同的逻辑。

Java 中的字符串是对象,因此您的 toString 方法签名应为public String toString().

于 2013-10-15T22:54:37.893 回答