Search code examples
javajava.util.scannersystem.in

java, getting user input through scanner and system.in


how can I give a condition on an input from "system.in" that will halt the program until the right value is inserted?

for exemple, I'm waiting for an INT from the user, 1,2,3,4 or 5 the user inputs "hello"

how can i give the user a message of "Invalid input, try again" and keep the program at halt until he does give the right one?

update: I didnt came so you can write my code, right now it looks something like this:

            int j=UserIn.nextInt();

            switch (j) {
            case 1:
                break;

            case 2:
                writetoDic(word, "dict.txt"); 
                break;

            case 3:
                word = correction;
                break;

i'm asking that, if im getiing something else than an int from the user, how can i ask the user to give a valid argument instead of just getting an error?


Solution

  • You need to use a loop. I don't think you actually mean halt the program, but actually preventing to program to proceed until valid input. You can do something like this

    Scanner scanner = new Scanner(System.in);
    int num;
    
    while (true) {
        try {
            System.out.println("Enter a number: ");
            num = scanner.nextInt();
            if (num >= 1 && num <= 5) {
                break;
            }
        } catch (InputMistmatchException ex){
            System.err.println("Input needs to be a number between 1 and 5, dummy.");
        }
    }
    

    Program will run if not between 1 and 5 and not an integer