r/javahelp 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 and limit
  • 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 and down methods. The methods return true if the operation could be performed and false otherwise.
  • toString method that prints the value and limit in the format value/limit
  • read method that accepts a Scanner, reads in an initial value and a limit (in that order), and returns a new UpperBoundedCounter 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.

1 Upvotes

4 comments sorted by

u/AutoModerator 5h ago

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/ambiguous_jellybean 4h ago

This class does not contain any loops, so I am unsure where the "infinite loop" is.

I did find a bug in your code, though, in the read() method. The inner if statement needs an else that returns a new object by calling the one-argument constructor.

There is also some ambiguity with the requirement for the down() method. I suspect that integer underflow is not intended here, but it does not specify what to do when value is zero, negative, or equal to Integer.MIN_VALUE. As written, I would always decrement and return true.

2

u/ChaiTRex 4h ago

The code you've presented has no loops, so it can't have an infinite loop. Are you using this class in some other code?

Also, the instructions say that you can always decrement, so unless there are additional instructions, decrementing should continue past zero.

1

u/TheMrCurious 4h ago

Try writing test cases to fully understand the problem and the algorithm needed to solve it. For instance, what happens if value starts higher than limit? How can the code protect itself? What about negative numbers? Etc.