我想从文件中读取数字 (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("");
}
根据您的文件,我将这样做:
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[][]
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)