我正在使用扫描仪读取文件。该文件的格式为第一行是数组的维度。下一行包含第一行,下一行包含第二行,依此类推。示例文件:
3 3 1 2 3 4 5 6 7 8 9
The problem I keep running into is that my array values seem to be all 9. The file is in ints but I need them in doubles. I also have a lot of print statements in there as I am trying to debug what was going on. My exception handling isn't finished. I will go back and beef that up after I can instantiate the array correctly. Any pointers would be appreciated. For example: a better way of getting the dimensions and instantiating the array with just opening the file once.
Updated but getting a nullPointerException
public class Help implements TopoMapInterface {
private String filename;
private File mapfile;
public double[][] baseMap;
public double[][] enMap;
public int enhancementLevel;
public Help(String filename) throws FileNotFoundException,
InvalidFileFormatException {
this.filename = filename;
System.out.println("Reading in file: " + filename);
String number = "";
int row = 0;
int col = 0;
int count = 0;
try {
Scanner inputFile = new Scanner(new File(filename));
while (inputFile.hasNextInt()) {
row = Integer.parseInt(inputFile.next());
col = Integer.parseInt(inputFile.next());
System.out.println("Row : " + row);
System.out.println("Col : " + col);
baseMap = new double[row][col];
System.out.println(baseMap[2][4]);
for (int i = 0; i < baseMap.length; i++){
for (int j = 0; j < baseMap[i].length; j++){
baseMap[i][j] = Double.parseDouble(inputFile.next());
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
最佳答案
假设您的第一行的值是先行,然后列
我会这样做
int row = Double.parseDouble(inputFile.next());
int col = Double.parseDouble(inputFile.next());
for (int i = 0;i<row;i++){
for(j=0;j<col;j++)
{
baseMap[i][j]=Double.parseDouble(inputFile.next());
}}
这应该根据需要将所有值存储为双倍,我认为这是从文件读取后更简单的存储方法。
我想我的问题是正确的!
关于java - 二维数组的构造函数仅包含最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691858/