0

My program prompts the user to enter an Integer.

For example:

int numbers = keyboard.nextInt(); 

So, when they enter a letter, my Java program immediately crashes.

How can I display an error message instead of having Java crashing the program?

Unheilig
  • 15,690
  • 193
  • 65
  • 96
Survivorr
  • 73
  • 1
  • 10

3 Answers3

0

By using a try-catch statement:

Scanner scan = new Scanner(System.in);

boolean validInput = false;
int val = 0;

while(!validInput) {
    try {
        val = scan.nextInt();
        validInput = true;
    } catch(InputMismatchException e) {
        System.out.println("Please enter an integer!");
        scan.next();
    }
}

System.out.println("You entered: " + val);
Chris
  • 2,265
  • 4
  • 21
  • 49
  • It would be better to catch an inputmismatchexception – jthort Feb 28 '17 at 20:36
  • @jthort thanks, I was just about to google the exact exception. I will update the answer – Chris Feb 28 '17 at 20:37
  • error: cannot find symbol catch (InputMismatchException e) { ^ – Survivorr Feb 28 '17 at 20:47
  • @Survivorr are you using java or javascript? Your post is tagged as both but the syntax you provided appears to be java. Also you need to import `InputMismatchException` with `import java.util.InputMismatchException` – Chris Feb 28 '17 at 20:48
  • @Tom I added `scan.next()` to solve the issue. Can you remove your down vote now? – Chris Mar 01 '17 at 21:15
  • Sure. I also removed my obsolete comments. – Tom Mar 01 '17 at 21:20
0

This is a situation where exception comes in handy.

An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.

An exception can occur for many different reasons. Following are some scenarios where an exception occurs.

A user has entered an invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has run out of memory.

So in your case surround the code which might cause the error with try block..

when the use will input the wrong type instead of terminating the you can decide what to display on screen.

try{
//code that can produce error i.e. input statement
}catch(Exception e){
System.out.println("Enter Integer");
}
-1

You can do so by taking an input as string and checking whether it's a number by regex, e.g.:

public static void main(String[] args) throws Exception {
    Scanner scanner = new Scanner(System.in);
    String input = scanner.next();
    if(!input.matches("[\\-]?[0-9]+")){
        System.out.println("Wrong input");
    }
}
Darshan Mehta
  • 27,835
  • 7
  • 53
  • 81
  • Does this cover negative integers? – Stefan Freitag Feb 28 '17 at 20:57
  • 1
    @StefanFreitag No, according to the regex it is matching strings made up of the digits `0-9`. Also the String input would need to be cast to an `int` with `Integer.parseInt(input)`. A regex string to pickup negatives would be `-*[0-9]+` (assuming `-` is a literal, otherwise you need to escape it with `\-`) – Chris Feb 28 '17 at 21:08
  • @DarshanMehta this doesn't account for the case of `1e5` which I believe is a valid integer for Java's scanner. – Chris Feb 28 '17 at 21:09
  • 1
    @StefanFreitag I have updated the answer. It will now accept negative numbers too. – Darshan Mehta Feb 28 '17 at 21:10