你的問題是你沒有處理你正在捕捉的錯誤。 如果您提供nextInt()
方法的數字格式錯誤,那麼InputMismatchException
將爲thrown
。然後因爲catch
什麼都不做,循環將繼續(從begining開始)和掃描儀將讀取相同的不正確的值,依此類推......
所以不是這樣的:
catch (InputMismatchException e) {
}
試試這個:
catch (InputMismatchException e) {
System.out.println("Wrong number entered.");
scanner.nextLine();
}
這樣你就會強制scanner
移過最後一個不正確的輸入。
編輯:
你循環也斷了,因爲你做break
讀取輸入後。在這種情況下,如果你將負數放在break
之內,也不會檢查循環條件。取出break
聲明,它會按預期工作:
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]);
}
輸出:
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
這就是爲什麼我把break ?,所以,我認爲,一旦存儲完成,程序就會離開 – dumas 2014-09-01 09:28:06
爲什麼你甚至有檢查標誌? – john 2014-09-01 09:29:03
另外,什麼是R&C? – Pranalee 2014-09-01 09:29:05