System.in 多行输入,StringIndexOutOfBoundsException?

System.in multiline input, StringIndexOutOfBoundsException?

我正在尝试扫描要插入到二维数组中的多行输入,但出现越界异常。

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})。

input.nextLine() 读取一行,没有 \n。因此它只有returns"AB"。您对 .replace("\n", "").replace("\r", "") 的调用无效。

您可能应该多次调用 input.nextLine,直到获得所需的所有输入。