1

So, I'm using nextInt() to get integer inputs from the user in the command line. However, my question is; when the user does not enter an integer, i.e. just presses enter without entering anything, the nextInt() does not terminate but continues to prompt the user until an integer is entered by the user. Is it possible to take that first "no input" as an input and then return an error message saying that no integer was inputted? Thanks in advance!

krandiash
  • 165
  • 3
  • 11
  • possible duplicate of [Blank input from scanner - java](http://stackoverflow.com/questions/5689325/blank-input-from-scanner-java) – assylias Aug 26 '12 at 08:47
  • If you add an [sscce](http://sscce.org) and you specify that you are using java.util.Scanner, it will help everybody. – gontard Aug 26 '12 at 08:58

5 Answers5

1
 String line = null;
    int val = 0;
    try {
      BufferedReader is = new BufferedReader(
        new InputStreamReader(System.in));
      line = is.readLine();
      val = Integer.parseInt(line);
    } catch (NumberFormatException ex) {
      System.err.println("Not a valid number: " + line);
    } catch (IOException e) {
      System.err.println("Unexpected IO ERROR: " + e);
    }
    System.out.println("I read this number: " + val);
Mohammod Hossain
  • 4,134
  • 2
  • 26
  • 37
0

I am assuming that you are using a Scanner. If so, then you would want to specify which delimiter would you use. Something like this:

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.getProperty("line.separator")); 
while (scanner.hasNextInt()){
    int i = sc.nextInt();
    /** your code **/
}
Sujay
  • 6,753
  • 2
  • 30
  • 49
0

You could do a try/catch.

String input = ....
try {
    int x = Integer.parseInt(input);
    System.out.println(x);
}
catch(NumberFormatException nFE) {
    System.out.println("Not an Integer");
}
aug
  • 11,138
  • 9
  • 72
  • 93
0

Instead of integer try taking the input as string. If the string is empty then the error you mentioned shall be raised else convert the string to integer. I don't know what your program flow so its a general idea, parsing of string will be required according to the input. Also before using this method you should ensure that nothing else than integers are given as input.

Srijan
  • 1,234
  • 1
  • 13
  • 26
0

Try this

 int number;
 boolean is_valid;

    do {
        try {
            System.out.print("Enter Number :");
            Scanner kbd = new Scanner(System.in);
            number = kbd.nextInt();
            is_valid = true;
        } catch (Exception e) {
            System.out.println("Invalid Integer ");
            is_valid = false;
        }
    } while (!is_valid);
mssb
  • 878
  • 1
  • 8
  • 19