2015-07-05 25 views
0

我想掃描一個多行輸入插入到二維數組中,但我得到了一個超出界限的異常。System.in多行輸入,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})。

回答

4

input.nextLine()只讀一行,沒有\n。因此它只返回「AB」。您撥打.replace("\n", "").replace("\r", "")的電話無效。

您應該多次撥打input.nextLine,直到獲得所有您需要的輸入。

+0

有沒有一種方法來讀取多行?輸入從其他地方直接複製/粘貼到IDE中。 – gator

+1

@riista我看着它。 'nextLine()'使用內部正則表達式模式來確定一行的結尾。你可以用'新的掃描儀(新的InputStreamReader(System.in),「SomeRegExPattern」))初始化掃描儀;'然後使用'next()'而不是'nextLine()'來讀取輸入。這會導致next()讀取輸入,直到遇到正則表達式定義的分隔符(默認爲WHITESPACE)。不過,我不確定你應該使用哪種模式。你如何確定輸入的結束? – Eran

+0

輸入的結尾是沒有剩餘字符的時候。空格是有效的輸入,新行也是如此。 – gator