我正在尝试编写接收单词并将其字母存储在多维数组中的代码。现在,我得到一个数组索引超出范围的异常,我不知道为什么。我正在使用以下输入进行测试:
2
SEND
MORE
MONEY
(我只想在阵列中输入'SEND'和'MORE'的字母。)
我在指示的行处得到一个ArrayIndexOutOfBoundsException:2。这是我的代码:
Scanner keyboard = new Scanner(System.in);
int n = keyboard.nextInt();
keyboard.nextLine();
String[] addends = new String[n];
for (int i = 0; i < n; i++) {
addends[i] = keyboard.nextLine();
}
String sum = keyboard.nextLine();
int maxWordLength = 0;
for (int i = 0; i < n; i++)
if (addends[i].length() > maxWordLength)
maxWordLength = addends[i].length();
char[][] letters = new char[maxWordLength][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < addends[i].length(); j++)
letters[i][j] = addends[i].charAt(j); //Getting exception here.
//Test that letters were added correctly
for (int i = 0; i < n; i++)
for (int j = 0; j < addends[i].length(); j++)
System.out.print(letters[i][j]);
答案 0 :(得分:3)
char[][] letters = new char[maxWordLength][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < addends[i].length(); j++)
letters[i][j] = addends[i].charAt(j);
通过检查显而易见,第一行应该是
char[][] letters = new char[n][maxWordLength];
或者您在以下循环中混淆了i
和j
。
答案 1 :(得分:0)
char[][] letters = new char[maxWordLength][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < addends[i].length(); j++)
letters[i][j] = addends[i].charAt(j);
你对i和j的条件不匹配;我应该停在加数[i] .length()和j应该停止