0

Im currently trying to build a code that prevents wrong user input (storing a char/string to a integer, e.g.) but Im not being able to make it to work...

    public static void main(String[] args) {
    int num=0, option=0;
    boolean keep=true;
    
    Scanner scan = new Scanner(System.in);
    
    while(keep) {
        System.out.println("1 - Test Exception.");
        System.out.println("2 - Out.");
        
        option = scan.nextInt();
        switch(option) {
        
        case 1:
            System.out.println("Write a number: ");
            if(scan.hasNextInt()) {
                num = scan.nextInt();
            }
            else {
                System.out.println("Wrong input...");
            }
            break;
        case 2:
            keep=false;
            System.out.println("Bye !");
            break;
        }
        
    }

}

As soon as I input a char/string, the code stops working. The exception occurs in the line option = scan.nextInt();

What am I missing?

Agustin
  • 3
  • 5
  • you shouldn't do checks like 'hasNextInt()', it doesn't has a nextInt untill you enter it. – Stultuske Jun 11 '21 at 14:16
  • What you are missing is that nextInt only reads ints, it's not meant to read chars or Strings – Stultuske Jun 11 '21 at 14:22
  • but the exception is allready telling you that, so what is your problem? – Stultuske Jun 11 '21 at 14:23
  • Hey thanks for answering ! Sorry for not being clear enough. I want the code to NOT crash when the user inputs a wrong data type. I do want the variable to be a integer but if the user misread and enters a char, e.g., I want the code to write something like "Hey, you entered something wrong..." and let the user enter a new "correct" value. – Agustin Jun 11 '21 at 14:36

4 Answers4

0

you are input type is only integer how did you pass the string/char value. use Integer.parseInt(option) if your input is string/char.

0

You expect that the user enters an int, however, the user is free to enter whatever the user pleases. Therefore you need to ensure that the input can be parsed.

String userInput = scan.next(); //scan the input
int value;
try {
    value = Integer.parseInt(userInput); // try to parse the "number" to int
} catch (NumberFormatException e) {
    System.out.println("Hey, you entered something wrong...");
    // now you can ask the user again to enter something
}
0

I fixed your version of the code a little, so it is now working with chars/Strings. I've tried to modify as little as possible.

public static void main(String[] args) {
    int num=0, option=0;
    String input;
    boolean keep=true;

    Scanner scan = new Scanner(System.in);

    while(keep) {
        System.out.println("1 - Test Exception.");
        System.out.println("2 - Out.");

        input = scan.next();
        
        try{
           option = Integer.parseInt(input);
        } 
        catch (NumberFormatException exception){
           System.out.println("Wrong input");
           continue;
        }

        switch(option) {

        case 1:
            System.out.println("Write a number: ");
            if(scan.hasNextInt()) {
                num = scan.nextInt();
            }
            else {
                System.out.println("Wrong input...");
            }
            break;
        case 2:
            keep=false;
            System.out.println("Bye !");
        }

    }

}

The Scanner is now using the next() function, which is returning the next entered chars submitted with enter.

In the try block the function Integer.parseInt(input) checks, if the given string is an Integer, otherwise the NumberFormatException is thrown and immediatly catched. In this case the continue statement skips the following code in the while-loop and starts it from the beginning.

So after the try-catch Block, you can be sure, that option is an Integer and the switch case is working.

-1

You could move option declaration inside the loop and declare it with var so that you can assign anything to it. Then you could use .getClass() method to check whether the input is equal to num (that is declared as int, so it will be true only if the scan is also int).

System.out.println("Write a number: ");
var x = scan.next();
if(x.getClass() == num.getClass()) {
    num = x
}
else {
    System.out.println("Wrong input...");
}
Fabio R.
  • 393
  • 3
  • 15
  • `x.getClass()` will always return `class java.lang.String`. => `x.getClass() == String.class` will always be true because `next()` returns a `String`. – Beru Jun 11 '21 at 14:39
  • @Beru that's right, my bad, I misread documentation. – Fabio R. Jun 11 '21 at 15:33