javastringwhile-loopdo-whileisnumeric

While loop input int validation


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

Solution

  • 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");
    }