问题描述
我想从文件中读取一个数字网格(n * n),然后将它们复制到一个多维数组中,一次复制一个int。我有代码读取文件并打印出来,但不知道如何获取每个int。我认为我需要splitstring方法和一个空白的定界符才能使用每个字符,但是在此之后我不确定。我也想将空白字符更改为0,但这可以等待!
I want to read in a grid of numbers (n*n) from a file and copy them into a multidimensional array, one int at a time. I have the code to read in the file and print it out, but dont know how to take each int. I think i need to splitstring method and a blank delimiter "" in order to take every charcter, but after that im not sure. I would also like to change blank characters to 0, but that can wait!
这是我到目前为止所获得的,尽管它不起作用。
This is what i have got so far, although it doesnt work.
while (count <81 && (s = br.readLine()) != null)
{
count++;
String[] splitStr = s.split("");
String first = splitStr[number];
System.out.println(s);
number++;
}
fr.close();
}
示例文件如下(需要空格):
A sample file is like this(the spaces are needed):
26 84
897 426
4 7
492
4 5
158
6 5
325 169
95 31
基本上我知道如何读取文件并打印出来,但是不知道如何从读取器中获取数据并将其放入多维数组中。
Basically i know how to read in the file and print it out, but dont know how to take the data from the reader and put it in a multidimensional array.
我刚刚尝试过这,但它说无法从String []转换为String
I have just tried this, but it says 'cannot covernt from String[] to 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("");
}
推荐答案
基于您的文件,这就是我的处理方式:
Based on your file this is how I would do it:
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 [] []
。
At the end of this code, you will have a list of int[]
which can be easily turned into an int[][]
.
这篇关于将文件读入多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!