我想从一个文件中读取一个数字网格 (n*n) 并将它们复制到一个多维数组中,一次一个 int。我有读取文件并将其打印出来的代码,但不知道如何获取每个 int。我想我需要拆分字符串方法和一个空白定界符“”才能获取每个字符,但之后我不确定。我也想将空白字符更改为 0,但这可以等待!
这是我到目前为止所得到的,尽管它不起作用。
while (count <81 && (s = br.readLine()) != null)
{
count++;
String[] splitStr = s.split("");
String first = splitStr[number];
System.out.println(s);
number++;
}
fr.close();
}
示例文件是这样的(需要空格):
26 84
897 426
4 7
492
4 5
158
6 5
325 169
95 31
基本上我知道如何读取文件并将其打印出来,但不知道如何从阅读器中获取数据并将其放入多维数组中。
我刚试过这个,但它说“无法从 String[] 转换为 String”
while (count <81 && (s = br.readLine()) != null)
{
for (int i = 0; i<9; i++){
for (int j = 0; j<9; j++)
grid[i][j] = s.split("");
}
最佳答案
根据您的文件,我会这样做:
Lint<int[]> ret = new ArrayList<int[]>();
Scanner fIn = new Scanner(new File("pathToFile"));
while (fIn.hasNextLine()) {
// read a line, and turn it into the characters
String[] oneLine = fIn.nextLine().split("");
int[] intLine = new int[oneLine.length()];
// we turn the characters into ints
for(int i =0; i < intLine.length; i++){
if (oneLine[i].trim().equals(""))
intLine[i] = 0;
else
intLine[i] = Integer.parseInt(oneLine[i].trim());
}
// and then add the int[] to our output
ret.add(intLine):
}
在这段代码的最后,您将得到一个 int[]
的列表,它可以很容易地变成一个 int[][]
。
关于java - 将文件读入多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3968859/