0

I have to build a user input template where you can enter a number between 100 and 200. If you type "goodbye", it needs to exit, if you enter a letter, symbol, number outside the range, etc. it needs to prompt you to try again. if you enter a number within the range, it will move on to another question (I haven't included that in the code below).

I got almost everything to work. If you enter a correct number the first time, it works. The "goodbye" and wrong character functions also work. BUT if you enter the wrong character (number or letter) and then, when it prompts you to try again, you put a CORRECT number in the range, it does not accept it and again prompts you to try again.

I need to figure out how to input a wrong character (such as a letter or number outside of range), and then when it prompts you to try again and you put a number between 100-200, it works and exits the loop (which will enable it to go on to the next question/loop).

Here is my code:

Scanner console = new Scanner(System.in);
    String Input;
    int Number;
    boolean isValid = true;        
        do {
        System.out.println("Enter a valid number:");
        Input = console.nextLine();
           if (Input.equals("goodbye") || Input.equals("GOODBYE")){
               System.out.println("You have left");
              System.exit(0);
           }
        char[] numberTester = Input.toCharArray();
       for (int i = 0; i<Input.length(); i++){
           Character currentChar = new Character (numberTester[i]);
           if (!currentChar.isDigit(numberTester[i])){
             isValid = false;
             System.out.println("Invalid. Try again.");
              i = Input.length();
           }
           if (isValid == true){
           Number = Integer.parseInt(Input);    
           if (Number < 100 || Number > 200){
             isValid = false;
             System.out.println("Invalid. Try again.");
               }
           }
       } 
        } while (isValid == false);
}
        }
5
  • 1
    Aside: It is coding convention in Java that variable names start with lowercase letters Commented Feb 6, 2016 at 18:23
  • 2
    You're never setting isValid to true when the input is valid. Therefore, if isValid is set to false once (like you are saying), it will never exit the loop, even if the input is valid. Commented Feb 6, 2016 at 18:24
  • 1
    You will be better off using String.equalsIgnoreCase() instead of String.equals() twice. Also, you can use try-catch with Integer.parseInt and avoid your for loop altogether. Commented Feb 6, 2016 at 18:33
  • @pdn1227 And if you are adamant at checking instead of catching NumberFormatException do 'char c = input.charAt(i); if (c < '0' || c > '9')' AND close the for loop before "if (isValid == true)". Commented Feb 6, 2016 at 18:36
  • @cricket_007 Yeah I know. I changed the names of the variables for this post to clarify, since my names weren't as specific to begin with. Just forgot to remove the caps before posting. Commented Feb 6, 2016 at 18:53

3 Answers 3

1

In the beginning your isValid flag is set true. Your do-while loop runs while this flag is false. If you enter something valid in your first round it quits the loop. But if you enter something invalid you set your flag to false and never back again, so it loops forever.
Setting your isValid flag true as first statement in your do while loop should solve your problem.

[...]
do{
    isValid = true;
    [...]
} while (isValid == false);
Sign up to request clarification or add additional context in comments.

2 Comments

Also for loop should only enclose the check for digits otherwise an input with non-digit in second character will throw NumberFormatException.
That worked perfectly, thank you! It does exactly what it should now.
0

It looks like the issue is coming from the fact that once you set the isValid variable to false, it never becomes true, so the do-while loop will loop infinitely.

One way to fix this would be to to set the isValid variable to true at the beginning of each cycle of the do-while loop, so that if nothing triggers it to become false within the loop, the loop will be exited at the end since the condition will not be true.

1 Comment

Isn't that what ArcticLord posted?
0

I think the purpose of this assignment is to learn how to handle exceptions. parseInt will throw a NumberFormatException. Use this to your advantage instead of that toCharArray nonsense.

public static void main(String args[]) {

    Scanner console = new Scanner(System.in);
    String input;
    int number;
    boolean isValid;

    do {
        isValid = true; // reset the validity
        System.out.print("Enter a valid number: ");
        input = console.nextLine();
        if (input.equalsIgnoreCase("goodbye")) {
            System.out.println("You have left");
            System.exit(0);
        }

        try {
            number = Integer.parseInt(input);
            if (number < 100 || number > 200) {
                isValid = false;
                System.out.println("Invalid. Try again.");
            }
        } catch (NumberFormatException e) {
            isValid = false;
            System.out.println("Invalid. Not a number. Try again.");
        }

    } while (!isValid);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.