我正试图扫描一个多行输入,以便插入到一个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})。
发布于 2015-07-05 06:08:45
input.nextLine()只读取一行,没有\n。因此,它只返回"AB“。您对.replace("\n", "").replace("\r", "")的调用没有任何效果。
在得到所需的所有输入之前,您可能应该多次调用input.nextLine。
https://stackoverflow.com/questions/31227594
复制相似问题