[英]java.util.InputMismatchException error when scanning from a .txt file
[英]How to read the integers from the .txt file which contains 2-D array, i am getting java.util.InputMismatchException
所以我必須從.txt文件中讀取一個矩陣,其格式如下。
problemMatrix = [[101, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30], [31, 32, 33, 34, 35, 36, 37, 38, 9, 40], [41, 42, 43, 44, 45, 46, 47, 28, 49, 50], [51, 52, 53, 54, 55, 56, 57, 58, 59, 60], [61, 62, 63, 64, 65, 66, 67, 68, 69, 70], [71, 72, 73, 7, 75, 76, 77, 78, 79, 80], [81, 82, 83, 84, 85, 86, 87, 88, 89, 90], [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]
我已經編寫了代碼來計算行和列。 我編寫了這段代碼來獲取[i] [j]索引中的整數值。
int [][] input= new int[rows][cols];
matrix = new Scanner(new File("test.txt"));
matrix.useDelimiter("[ ,\r\n\t=]");
try{
for(int i=0; i<rows; i++){
for(int j = 0;j<cols;j++){
input[i][j]=matrix.nextInt();
System.out.print(input[i][j] + " ");
}
System.out.println();
}
}
catch(InputMismatchException e){
System.out.println(e);
}
但是這給了我異常的InputMismatchException
。 有什么建議么。 我不明白如何更改掃描儀的分隔符。 謝謝。
我認為問題在於你的正則表達式。 正則表達式[ ,\\r\\n\\t=]
表示“匹配任何一個 ,
\\r
, \\n
, \\t
或=
。 請注意,它不匹配[
或]
。
您應該在方括號中包含[
和]
,並確保它們已被轉義,這應該有所幫助。 您可能還遇到多個分隔符的問題,導致您的掃描程序嘗試解析空字符串,因此您希望正則表達式將這些字符中的多個匹配在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.