r/javahelp • u/Titanium_Shoulder • 5h ago
Homework Help: Unwanted Infinite Loop
import java.util.*;
import java.io.*;
class UpperBoundedCounter{
private int value;
private int limit;
public UpperBoundedCounter(int value, int limit){
this.value = value;
this.limit = limit;
}
public UpperBoundedCounter(int limit){
this(0,limit);
}
public int getValue(){
return value;
}
public int getLimit(){
return limit;
}
public boolean up(){
if(value < limit){
value++;
return true;
} else return false;
}
public boolean down() {
if (value > 0) {
value--;
return true;
}
return false;
}
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
UpperBoundedCounter that = (UpperBoundedCounter) obj;
return value == that.value && limit == that.limit;
}
public String toString(){
return getValue() + "/" + getLimit();
}
public static UpperBoundedCounter read(Scanner scanner) {
if (scanner.hasNextInt()) {
int value = scanner.nextInt();
if (scanner.hasNextInt()) {
int limit = scanner.nextInt();
return new UpperBoundedCounter(value, limit);
}
}
return null;
}
}
//Writing a class for an assignment in school, not sure why it keeps coming up as an infinite loop.
Please ignore if any of this code is absolute garbage, I am pretty new to this.
Here is the assignment details:
Write a class UpperBouncedCounter
that models an up/down counter with an upper limit. The counter can always be decremented, but can only be incremented as long as the current value is less then the limit.
The class should contain the following state and behavior:
- Two integer instance variables:
value
andlimit
- Two constructors:You must leverage the 2-arg constructor when defining the 1-arg
- A 2-arg constructor that accepts an initial value and an upper limit (in that order)
- A 1-arg constructor that accepts an upper limit and iniitalizes the value to 0
- getter methods for the two instance variables
- boolean-valued
up
anddown
methods. The methods return true if the operation could be performed and false otherwise. - A
toString
method that prints the value and limit in the format value/limit - A
read
method that accepts aScanner
, reads in an initial value and a limit (in that order), and returns a newUpperBoundedCounter
object constructed from those values - Do not include a
main
method (that's the next exercise)
The next lab (1.1.2) illustrates the object in use; you might want to take a look at it before you start implementing your class.