简体   繁体   中英

Endless loop with try and catch JAVA

so what I am trying to do is have the user input a valid coordinate in a matrix, that is an INT which is greater than -1,

Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;  
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>R))  && check) {
    System.out.print("Please enter a valid row number:\t");
    try { 
        coordinates[0]=scanner.nextInt(); 
        break; 
    }
    catch (InputMismatchException e) {
    }
}
while (((coordinates[1]<0)||(coordinates[1]>C)) && check) {
    System.out.print("Please enter a valid col number:\t");
    try { 
        coordinates[1]=scanner.nextInt(); 
        break; 
    }
    catch (InputMismatchException e) {
    }       
}

the problem is that it loops endlessly after entering a not valid input int R is the size of the row int C is the size of the collumn

If by "not valid input" you mean "not any kind of integer", then your scanner will fail each time it tries to read another integer, so you'll hit your catch , and do nothing to stop the loop. Maybe you intended to set check to false in such circumstances? Or maybe you meant to put the break in each catch ?

Using a break when a valid integer is read isn't right, because it might be a negative integer, which your loop guard says you don't want.

Your problem is that you're not handling the error you're catching. If you'll provide wrong format of number for the nextInt() method, then the InputMismatchException will be thrown . Then because the catch does nothing, the loop will continue (start from begining) and the scanner will read the same incorrect value, and so on...

So instead of this:

catch (InputMismatchException e) {
}  

Try this:

catch (InputMismatchException e) {
    System.out.println("Wrong number entered.");
    scanner.nextLine();
}   

This way you'll force scanner to move past the last incorrect input.

EDIT:

You're loop is also broken because you do break after reading the input. In that case if you'll put the negative number you'll break as well and won't check the loop condition. Remove the break statement and it will work as expected:

while (((coordinates[0]<0)||(coordinates[0]>R))  && check) {
    System.out.print("Please enter a valid row number:\t");
    try { 
        coordinates[0]=scanner.nextInt(); 
    }
    catch (InputMismatchException e) {
        System.out.println("That's not a valid number.");
        scanner.nextLine();
    }
}

EDIT2:

public static void main(final String args[])
{
    int maxRowsNumber = 10;
    int maxColsNumber = 10;
    Scanner scanner = new Scanner (System.in);
    int coordinates[] = new int[2];
    coordinates[0]=-1;  
    coordinates[1]=-1;
    boolean check = true;
    while (((coordinates[0]<0)||(coordinates[0]>maxRowsNumber))  && check) {
        System.out.print("Please enter a valid row number:\t");
        try { 
            coordinates[0]=scanner.nextInt(); 
        }
        catch (InputMismatchException e) {
            System.out.println("That's not a valid number.");
            scanner.nextLine();
        }
    }
    while (((coordinates[1]<0)||(coordinates[1]>maxColsNumber)) && check) {
        System.out.print("Please enter a valid col number:\t");
        try { 
            coordinates[1]=scanner.nextInt(); 
        }
        catch (InputMismatchException e) {
            System.out.println("That's not a valid number.");
            scanner.nextLine();
        }       
    }
    System.out.println("Inserted RowsNumber: " + coordinates[0]);
    System.out.println("Inserted RowsNumber: " + coordinates[1]);
}

Output:

Please enter a valid row number:    11
Please enter a valid row number:    22
Please enter a valid row number:    10
Please enter a valid col number:    11
Please enter a valid col number:    2
Inserted RowsNumber: 10
Inserted RowsNumber: 2

This is basically the same as what your doing, I just tried to improve it a little bit by removing hardcoded values, made variables more descriptive, and included input validations.

final int ROW = 0;
final int COL = 1;

int coordinates[] = new int[2];
coordinates[ROW] = -1;
coordinates[COL] = -1;
boolean isInputValid = true;

Scanner scanner = new Scanner(System.in);
do {
    try {
        System.out.print("Please enter a valid row number:\t");
        coordinates[ROW] = Integer.parseInt(scanner.nextLine());
    } catch (NumberFormatException nfe) {
        isInputValid = false; //if the input is not int
    }
} while (!isInputValid && (coordinates[ROW] < 0) //do this until the input is an int
        || (coordinates[ROW] > R));              //and it's also not less than 0 or greater than R


//same logic applies here
do {
    try {
        System.out.print("Please enter a valid col number:\t");
        coordinates[COL] = Integer.parseInt(scanner.nextLine());
    } catch (NumberFormatException nfe) {
        isInputValid = false;
    }
} while (!isInputValid && (coordinates[COL] < 0)
        || (coordinates[COL] > C));

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM