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
James Z
  • 12,209
  • 10
  • 24
  • 44
  • "*...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`. – Pshemo Nov 21 '22 at 17:34
  • 1
    Maybe you meant to use `nextLine()`? – Pshemo Nov 21 '22 at 17:34
  • BTW you never update `isNumeric` inside loop, so it wont end since condition of `while ((!isNumeric))` is based on `isNumeric`. – Pshemo Nov 21 '22 at 17:34

2 Answers2

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");
}
aatwork
  • 2,130
  • 4
  • 17
  • Or get rid of `isNumeric` variable and move test directly to condition like `while ((!num.matches("-?\\d+(\\.\\d+)?"))){...}` – Pshemo Nov 21 '22 at 17:33
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