Search code examples
javaexceptionuser-input

exception handling resulting in infite loop(java)


Hello I am a Java beginner.I wanted to make a method that takes an integer between 1 and 9. I am using the exception handler so that it can deal with wrong or mismatched input but it seems that it is only executing the statement "choice = input.nextInt()" once and my loop goes to infinite because of it.

Code is below:

import java.util.*;

public class Player{
    private int[] over;
    private int choice;
    private int coordinates[];
    private static Scanner input = new Scanner(System.in);


    public Player(){
        over = new int[5];
        for(int i = 0; i < 5; i++){
            over[i] = 1;
        }
        coordinates = new int[2];
        coordinates[0] = coordinates[1] = -1;
    }


    public void getChoice(){
            int choice = -1;
            boolean inputIsOk;
            do{
                System.out.print("Enter Your Choice: ");
                inputIsOk = true;
                try{
                    choice = input.nextInt();
                }
                catch(InputMismatchException e){
                    System.out.println("Invalid choice");
                    inputIsOk = false;
                }
                if(choice < 1 || choice > 9){
                    System.out.println("Enter Choice In Range(1-9)");
                    inputIsOk = false;
                }
            }while(!inputIsOk);
            System.out.println("You Entered "+choice);
    }
} 

And here is the testclass:

public class TestPlayer{
    public static void main(String args[]){
        Player p1 = new Player();
        p1.getChoice();
    }
}

Here is the ouput: First case When only integral choice is entered

harsh@harsh-Inspiron-3558:~/java/oxgame$ javac TestPlayer.java 
harsh@harsh-Inspiron-3558:~/java/oxgame$ java TestPlayer 
Enter Your Choice: 10
Enter Choice In Range(1-9)
Enter Your Choice: -1
Enter Choice In Range(1-9)
Enter Your Choice: 55
Enter Choice In Range(1-9)
Enter Your Choice: 5
You Entered 5

And Second when I enter wrong input:

Enter Your Choice: 10
Enter Choice In Range(1-9)
Enter Your Choice: 55
Enter Choice In Range(1-9)
Enter Your Choice:g
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
and it goes on....

Please help me,Thanks.


Solution

  • This will work

    try{ 
           choice = Integer.parseInt(input.next());
       } 
    catch(NumberFormatException e){
        System.out.println("Invalid choice");
        inputIsOk = false;
    } 
    

    Reason Being: Say Scanner read an Object from stream say typeCache. Until it won't get an Integer Value, buffer will not be flushed and typeCache will hold String until it is read using next()(or any equivalent).

    Code Of Scanner class:

        public int nextInt() {
        return nextInt(defaultRadix);
    }
    
    public int nextInt(int radix) {
        // Check cached result
        if ((typeCache != null) && (typeCache instanceof Integer)
            && this.radix == radix) {
            int val = ((Integer)typeCache).intValue();
            useTypeCache();
            return val;
        }.......
    

    Or Simply add input.next(); in your catch block and it will clear typeCache automatically.