gpt4 book ai didi

Java从文件中读取二维数组,数字用逗号分隔

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:26 24 4
gpt4 key购买 nike

这是我发现有助于读取二维数组的一些代码,但我遇到的问题是这仅在读取结构如下的数字列表时才有效:

73
56
30
75
80
ect..

我想要的是能够读取如下结构的多行:

1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1

我只想将每一行本质上导入为一个数组,同时像文本文件中的数组一样构建它们。我读过的所有内容都说要使用 scan.usedelimiter(",");但在我尝试使用它的任何地方,程序都会直接抛出回复“错误转换数字”的捕获。如果有人可以提供帮助,我将不胜感激。我还看到了一些有关对缓冲读取器使用 split 的信息,但我不知道使用哪个/为什么/如何更好。

    String filename = "res/test.txt"; // Finds the file you want to test.


try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);

int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}

最佳答案

我在这里提供我的代码。

public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}

public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}

关于Java从文件中读取二维数组,数字用逗号分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21300156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com