0

I am trying to use Scanner object sc to read in an integer from user's input and need to assess whether it's greater than 0. So I set the following OR conditions in the while() to check whether it's an empty line or the input number is less than 0. But the program does not take inputs after it encountered an invalid input. Any help is appreciated.

 Scanner sc = new Scanner(System.in);
 while (!sc.hasNextInt() || sc.nextInt() <= 0)
        {
            System.out.println("Invalid input\n the number needs to be greater than 0");
            sc.next();
        }
        int number = sc.nextInt(); 
1
  • 4
    For starters, your while loop is going to be consuming all of those nextInts. Commented Sep 16, 2013 at 3:38

1 Answer 1

1

The problem is probably that you're consuming the nextInt in the condition. You should read it into a variable:

package test;

import java.util.Scanner;

public class ScannerTest {
    public static void main(String[] arg) {
        Scanner sc = new Scanner(System.in);
        int input=-1;
        while(input<0){
            while (!sc.hasNextInt()) {
                if(sc.hasNext()){
                    String s = sc.next(); /* read things that are not Integers */
                    System.out.println("Invalid input:" + s);
                }
            }
            input = sc.nextInt();
            if(input<0){
                System.out.println("Please input a positive integer.");
            }
        }
        System.out.println("Valid input was "+input);
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Won't this end up in an endless loop if it encounters non-numeric input?
It will, but it solves the problem of not consuming the valid input while checking for the valid input.
umm... assignment within a condition head is ugly. You know, accidental assignment and stuff. Strong typing does not cut it IMO.
thanks David, but it still does not solve my problem with "int number = sc.nextInt(); ". After the program encounters an invalid input, it does not take the first input (it can only take the second input). Thanks
Edited to address your concerns. :)

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.