我的程序應該評估對資本陣列的用戶輸入。它看起來像我不斷收到這樣的錯誤消息:Java代碼outOfBoundsException
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 19
任何人都可以幫忙嗎?
package Capitol;
import java.util.Scanner;
public class Capitol {
static Scanner input = new Scanner(System.in).useDelimiter("\r\n");
public static void main(String[] args) {
int correctAnswer = 0;
String [][] grid = {
{"Alabama", "California", "Delaware", "Florida", "Georgia",
"Hawaii", "Idaho", "Kansas", "Lousiana", "Maryland", "New Mexico", "Oregon",
"Pennsylvania", "Rhode Island", "South Carolina", "Texas", "Utah", "Virgina",
"West Virginia"},
{"Montgomery", "Sacramento", "Dover", "Tallahassee", "Atlanta",
"Honolulu", "Boise", "Topeka", "Baton Rouge", "Annapolis", "San Jose", "Salem",
"Harrisburg", "Providence", "Columbia", "Austin", "Salt Lake City", "Richmond",
"Charleston"}};
for(int i = 0; i< grid.length; i++){
System.out.println("What is the capital of ?");
String capital = input.next();
for(int k =0; k <20; k++){
String answer = null;
grid[i][k] = answer;
if(capital.equalsIgnoreCase(answer)){
correctAnswer ++;
System.out.println("Your answer is correct");
}
else
System.out.println("The correct answer should be" + grid[i]);
}
}
System.out.println("The correct count is " + correctAnswer);
}
}
請添加您獲得的堆棧跟蹤。 – watery
在2d數組中,您可以獲取嵌套for循環的子數組長度。改變'k <20'爲'k