1

I’m having a problem with my code. my while loop 3 times when its meant to loop once i've tried everything i know and it's not working

import java.util.Scanner;

public class validInput {
    public static void main (String[] args) {
        Scanner key = new Scanner(System.in);

        System.out.print("Enter a number: ");
        String num = key.next();
        boolean isNumeric = true;
         isNumeric = num.matches("-?\\d+(\\.\\d+)?");

        while ((!isNumeric)) {
            System.out.println("You must enter an integer");
            num = key.next();
        }
        System.out.print("Valid");
    }
}
# outputs Enter a number: my first mistake
# You must enter an integer
# You must enter an integer
# You must enter an integer
# my first mistake
3
  • "...when its meant to loop once" what makes you think so? The key.next(); consumes single token, so when you write my first mistake the first next() will consume only my. Commented Nov 21, 2022 at 17:34
  • 1
    Maybe you meant to use nextLine()? Commented Nov 21, 2022 at 17:34
  • BTW you never update isNumeric inside loop, so it wont end since condition of while ((!isNumeric)) is based on isNumeric. Commented Nov 21, 2022 at 17:34

2 Answers 2

2

Check the while loop below. You forgot to update isNumeric value within loop.

public static void main (String[] args) {
    Scanner key = new Scanner(System.in);

    System.out.print("Enter a number: ");
    String num = key.next();
    boolean isNumeric = true;
     isNumeric = num.matches("-?\\d+(\\.\\d+)?");

    while ((!isNumeric)) {
        System.out.println("You must enter an integer");
        num = key.next();
        isNumeric = num.matches("-?\\d+(\\.\\d+)?");
    }
    System.out.print("Valid");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or get rid of isNumeric variable and move test directly to condition like while ((!num.matches("-?\\d+(\\.\\d+)?"))){...}
2

public class Eli {

public static void main(String[] args) {
    Scanner key = new Scanner(System.in);

    System.out.print("Enter a number: ");
    String num = key.nextLine();
    boolean isNumeric = true;
    isNumeric = num.matches("-?\\d+(\\.\\d+)?");

    while ((!isNumeric)) {
        System.out.println("You must enter an integer");
        num = key.nextLine();
        isNumeric = num.matches("-?\\d+(\\.\\d+)?");
    }
    System.out.print("Valid");

}

}

note: You have 2 mistakes *You wrote key.next() instead of key.nextLine() *You forgot to check inside the loop whether isNumeric and it didn't check correctness from the second input onwards

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.