Home > Back-end >  While loop input int validation
While loop input int validation

Time:11-22

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

CodePudding user response:

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

CodePudding user response:

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

  • Related