Shumsky
Shumsky

Reputation: 3

do while loop and user input issue

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

}

Upvotes: 0

Views: 270

Answers (2)

Ravi Sharma
Ravi Sharma

Reputation: 170

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

Upvotes: 0

Sankeeth Ganeswaran
Sankeeth Ganeswaran

Reputation: 477

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

}

Upvotes: 1

Related Questions