0

How do I validate if user input is a number? The number is from the main method and it's checked if it's a number in another method. It should return true if the input is a number and false if it's not.

What I have so far:

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

    System.out.print("Please, enter a number: ");
    int number = sc.nextInt();

    validateInput(number);
}

public static int validateInput(int num) {
    while(num <= 0)
        if(!sc.hasNextInt())
            System.out.print("INVALID INPUT, Try again...");
}

Output should be:

Please, enter a number: a
Invalid input, Try again...
Please, enter a number: 16
Valid input, thank you.
APerson
  • 8,140
  • 8
  • 35
  • 49
BbOii
  • 3
  • 4
  • possible duplicate of [What's the best way to check to see if a String represents an integer in Java?](http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-to-see-if-a-string-represents-an-integer-in-java) – APerson Nov 24 '14 at 23:04
  • Calling `sc.nextInt()` whenever the input is not an int will throw an exception. – Matt Coubrough Nov 24 '14 at 23:19

1 Answers1

0

There's a strong inconsistency in your logic . you're prompting a number , and with what do you want to compare it with ? This statement will be true as long as it's within the integer range

 while(num <= 0)
        if(!sc.hasNextInt())
            System.out.print("INVALID INPUT, Try again...");

it will be better if you can review what you want to achieve by either prompting one number and guessing it or either by generating a number randomly and then try to guess it .

mkwilfreid
  • 128
  • 2
  • 12