简体   繁体   English

从逗号分隔的文件中读取int到2D数组中

[英]Reading ints from file seperated by comma into a 2D array

My code is supposed to read in integer values separated by commas from a file into a 2D array. 我的代码应该将用逗号分隔的整数值从文件读入2D数组。 I am having trouble because of the commas. 由于逗号,我遇到了麻烦。 I cannot remove commas from the original text file. 我无法从原始文本文件中删除逗号。 Here is what is in the original text file. 这是原始文本文件中的内容。

1, 2, 3, 4, 5
6, 7, 8, 9, 0
6, 7, 1, 2, 5
6, 7, 8, 9, 0
5, 4, 3, 2, 1

Here is my attempt at doing it. 这是我的尝试。

int[][] m = new int[5][5];
for (int row = 0; row < 5; row++) {
    for (int col = 0; col < 5; col++) {
        m[row][col] = input.nextInt();
    }
}

This code gives me an InputMismatchException in line 4. 这段代码在第4行中为我提供了InputMismatchException。

I assume 'input' is a scanner. 我假设“输入”是扫描仪。 Update the delimiter to be either a newline or a comma, before you read anything from input: 在从输入中读取任何内容之前,请将定界符更新为换行符或逗号:

input.useDelimiter("\\n|\\s*,\\s*");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM