0

i wrote this code to control input so user cannot enter anything except integers but problem is that: when an Exception occures, the message in Exception block is continousely printed and never ends, what i can do ?

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int i=0;
    boolean success = false;
    
    System.out.println("Enter an int numbers :");
    
    while(!success) {//"while loop" will continue until user enters an integer
        try {
            i = scanner.nextInt();
            success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
            
        }catch(InputMismatchException e) {
            System.out.println(" enter only integers ");
        }
    }
    System.out.println(i);
}
amir
  • 3
  • 2

2 Answers2

1

you should add scanner.nextLine(); in your catch block

the explenation is that you need to clear the scanner and to do so you should use nextLine()

" To clear the Scanner and to use it again without destroying it, we can use the nextLine() method of the Scanner class, which scans the current line and then sets the Scanner to the next line to perform any other operations on the new line."

for more understanding visits the link

your code will look like this

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int i=0;
    boolean success = false;
    
    System.out.println("Enter an int numbers :");
    
    while(!success) {//"while loop" will continue until user enters an integer
        try {
            i = scanner.nextInt();
            success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
            
        }catch(InputMismatchException e) {
            System.out.println(" enter only integers ");
            scanner.nextLine();
        }
    }
    System.out.println(i);
}
0

Add scanner.nextLine(); in your try and catch block. Like this

while(!success) {//"while loop" will continue until user enters an integer
        try {
            i = scanner.nextInt();
            success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
            scanner.nextLine();
            
        }catch(InputMismatchException e) {
            System.out.println(" enter only integers ");
            scanner.nextLine();
        }
    }

You can also add just one scanner.nextLine() in the finaly block, which should be below catch

ErayZaxy
  • 66
  • 2
  • 8
  • that does not work , sorry because result of nextLine() is String and cannot be saved in i ( i is an integer) – amir Dec 27 '21 at 12:44
  • you dont' save it in nothing, just type scanner.nextLine(); after your success=true line – ErayZaxy Dec 27 '21 at 12:45