我知道这个网站上的人不喜欢帮助做家庭作业,可以理解的是,我也不会。但是,如果有人可以向我展示我在这个问题上所缺少的东西,或者指出正确的方向,那将不胜感激。我已经包括了作业指导,并且代码本身还有更多内容。预先谢谢!
/*
* Write the code for the RolloverCounter class below
*
* In this RolloverCounter.java file you will implement a RolloverCounter class that should include:
1) A private variable to store the current count.
2) Another private variable to store the maximum value this counter can count up to.
3) A constructor with a single integer parameter used to set the maximum counter value. The count should be set to 0.
4) An increment() method that increases the count value by 1, but sets it back to 0 if the count goes above the maximum. no parameters, returns nothing
5) A decrement() method that decreases the count value by 1, but sets it to the maximum value if it goes below 0. no parameters, returns nothing
6) A getCount() method that returns an integer of the current count value. no parameters.
7) A reset() method that sets the count value back to 0. no parameters, returns nothing.
Notes:
+ This class is meant to be like the values on a car's odometer readout that tick upwards through
the digits 0 to 9 and then roll back to 0. In this case, the maximum can be any positive number.
+ The count should always be a number between 0 and the maximum value that was set when the counter was created.
*/
public class RolloverCounter {
//TODO: Write the code for the class here.
//private variables
private int count;
private int max;
//constructor
public RolloverCounter(int maxCount) {
count = 0;
max = maxCount;
}
//methods
// increases the count value by 1, but sets it back to 0 if the count goes above the maximum.
// returns nothing
RolloverCounter myCount = new RolloverCounter(4);
public void increment() {
for (int i=1; i<=4; i++) {
myCount.increment();
}
}
// decreases the count value by 1, but sets it to the maximum value if it goes below 0.
// returns nothing
public void decrement() {
for (int i=1; i<=4; i++) {
myCount.decrement();
}
}
// returns an integer of the current count value.
public void getCount() {
myCount.getCount();
}
// sets the count value back to 0.
// returns nothing.
public void reset() {
myCount.reset();
}
}
首先要注意的是,您在类内部创建了该类的对象。
RolloverCounter myCount = new RolloverCounter(4);
您的笔记说有一个测试文件,它将为您运行代码。这意味着它将创建一个RolloverCounter对象并对其进行测试,如您的示例所示。您应该删除此行代码。
在增量和减量函数中都是看起来像这样的文本,
for (int i=1; i<=4; i++) {
myCount.increment();
}
for循环中指定的索引应取决于您在构造函数中初始化的内容。将此变量初始化为
max = maxCount;
在递增,递减和重置函数内部是对函数的递归调用。将会发生的是该函数将开始执行,然后调用自身,从而导致程序陷入该代码中。相反,这些应该由某些动作代替。所以
myCount.increment();
例如,应成为
count = count + 1;
但应进行更改,以使过渡功能起作用。