我想从文件中读取一个数字网格(n * n)并将它们复制到一个多维数组中,一次一个int。我有代码在文件中读取并打印出来,但不知道如何采取每个int。我想我需要splitstring方法和一个空白分隔符“”才能占用每个字符,但之后我不确定。我还想将空白字符更改为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("");
}
答案 0 :(得分:0)
编辑:您刚刚更新了帖子以包含示例输入文件,因此以下内容对您的案例不起作用。但是,原理是相同的 - 根据您想要的任何分隔符(在您的情况下为空格)标记您读取的行,然后将每个标记添加到行的列中。
您没有包含示例输入文件,因此我将做一些基本的假设。
假设输入文件的第一行是“n”,剩余部分是您想要读取的n x n个整数,则需要执行以下操作:
public static int[][] parseInput(final String fileName) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
int n = Integer.parseInt(reader.readLine());
int[][] result = new int[n][n];
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
String[] tokens = line.split("\\s");
for (int j = 0; j < n; j++) {
result[i][j] = Integer.parseInt(tokens[j]);
}
i++;
}
return result;
}
在这种情况下,示例输入文件将是:
3
1 2 3
4 5 6
7 8 9
这将导致3 x 3数组:
row 1 = { 1, 2, 3 }
row 2 = { 4, 5, 6 }
row 3 = { 7, 8, 9 }
如果您的输入文件没有“n”作为第一行,那么您可以等待初始化最终数组,直到您在第一行计算了令牌。
答案 1 :(得分:0)
private static int[][] readMatrix(BufferedReader br) throws IOException {
List<int[]> rows = new ArrayList<int[]>();
for (String s = br.readLine(); s != null; s = br.readLine()) {
String items[] = s.split(" ");
int[] row = new int[items.length];
for (int i = 0; i < items.length; ++i) {
row[i] = Integer.parseInt(items[i]);
}
rows.add(row);
}
return rows.toArray(new int[rows.size()][]);
}
答案 2 :(得分:0)
根据您的文件,我就是这样做的:
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[][]
。