我有一個問題是,當我輸入值爲數組2d的值有效,一切都完成了,但是當我輸入totalRow或totalColumn變量的錯誤值時,那麼我的輸入函數迫使我輸入double並在第二次獲取值。 這是我的代碼:輸入函數在Java中調用後得到錯誤的值?
public static void input() {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Input total totalRow: ");
totalRow = sc.nextInt();
// verify value input must be a positive integer and greater than zero
if (totalRow <= 0) {
System.out.println("Input value must be a positive integer and greater than zero!");
input();
}
System.out.println("Input total totalColumn: ");
totalColumn = sc.nextInt();
// verify value input must be a positive integer and greater than zero
if (totalRow <= 0) {
System.out.println("Input value must be a positive integer and greater than zero!");
input();
}
// check case array must be square array
if (totalRow != totalColumn) {
System.out.println("Array must be square!");
input();
}
} catch (InputMismatchException e) {
// print message when user input other than integer
System.out.println("Please input an integer!");
input();
}
// initialize array with totalRow and totalColumn
array = new char[totalRow][totalColumn];
// input value for array
for (int i = 0; i < totalRow; i++) {
for (int j = 0; j < totalColumn; j++) {
array[i][j] = sc.next().charAt(0);
}
}
}
例:I輸入2和用於totalRow和totalColumn:消息出現,我重新輸入爲2和2中,但我已經進入1 2 3 4 5 6 7 8對陣列和值從5
你可能不想使用遞歸來重複輸入 –