0

I'm trying to make a program where a user needs to input a random integer. If the user inputs a String I want an error message to pop out: "This is not a number" and after that restart the program until the user inputs a number. I got this so far and I'm stuck. I just get an error message if I input a string and program crashes.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int number = 0;


    do {
        System.out.println("Input a number!");
        number = scanner.nextInt();
        if (!scanner.hasNextInt()) {
            System.err.println("This is not a number");
        }

    } while (!scanner.hasNextInt());

    System.out.println("You entered: " + number);

}
1
  • Please add the error with which your program crashes. Commented Mar 26, 2020 at 18:41

2 Answers 2

1

You're getting an InputMisMatchException because if you input a string into a scanner.nextInt(), it will immediately give an error and stop the program before it does anything else, so it won't reach your if statement. One way to get around this issue is to instead receive user input as a string, try to parse it for an int, and end the loop if it doesn't throw an exception. This is my implementation:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String input = "";
    int number = 0;
    boolean end = true;


    do {
        System.out.println("Input a number!");
        input = scanner.nextLine();
        try {
            number = Integer.parseInt(input);
            end = true;
        } catch(Exception e) {
            System.err.println("This is not a number");
            end = false;
        } 

    } while (!end);

    System.out.println("You entered: " + number);

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Great and simple solution!
0

See if the below code can help achieve what you want to do.

public class Solution {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String number;
    do {
        System.out.println("Input a number!");
        number = scanner.next();
    } while (!isNumeric(number));

    System.out.println("You entered: " + number);
  }

  public static boolean isNumeric(final String str) {
    // null or empty
    if (str == null || str.length() == 0) {
        return false;
    }
    return str.chars().allMatch(Character::isDigit);
  }
}

Comments

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.