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);

}
Shumsky
  • 3
  • 1

3 Answers3

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);

}
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);
  }
}
Ravi Sharma
  • 150
  • 4
0

Do it as follows:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number = 0;
        boolean valid;
        do {
            valid = true;
            System.out.print("Input an integer: ");
            try {
                number = Integer.parseInt(scanner.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("This is not an integer. Try again.");
                valid = false;
            }
        } while (!valid);

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

A sample run:

Input an integer: a
This is not an integer. Try again.
Input an integer: 12.34
This is not an integer. Try again.
Input an integer: 45
You entered: 45

Notes:

  1. Use Scanner:nextLine instead of Scanner::nextInt; specially when you are dealing with input in a loop. Check Scanner is skipping nextLine() after using next() or nextFoo()? for more information.
  2. scanner.hasNextInt() should be used before scanner.nextInt() i.e.
    if(scanner.hasNextInt()) {
        number = scanner.nextInt();
    }
  1. If you want to input any number (not just integer), use number = Double.parseDouble(scanner.nextLine()); but make sure to declare number as a double variable i.e. as double number = 0.0.
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72