我正在尝试扫描多行输入以插入到2D数组中,但是我遇到了越界异常。
int width = 2;
int height = 2;
Scanner input = new Scanner(System.in);
String theInput = input.nextLine().replace("\n", "").replace("\r", "");
char[][] arr = new char[width][height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
arr[j][i] = theInput.charAt((width*i)+j);
}
}
当提示输入时,我输入以下内容:
AB
CD
//inputted as is
产生错误
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
这里发生了什么?我正在删除新行,因此应将其解析为ABCD
。相反,输入AB\nCD
甚至不会将正确的值插入arr
(它显示为{A,B,\,n}
)。
答案 0 :(得分:4)
input.nextLine()
只读取一行,而不是\n
。因此它只返回&#34; AB&#34;。您拨打.replace("\n", "").replace("\r", "")
的电话无效。
在获得所需的所有输入之前,您应该多次拨打input.nextLine
。