gpt4 book ai didi

java - 二维数组的构造函数只包含最后一个值

转载 作者:行者123 更新时间:2023-12-04 04:42:25 25 4
gpt4 key购买 nike

我正在使用扫描仪读取文件。该文件的格式为第一行是数组的维度。下一行包含第一行,下一行包含第二行,依此类推。示例文件:

3 31 2 3 4 5 67 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());
}}

这应该根据需要将所有值存储在 double 中,我认为这是从文件读取后更简单的存储方法。

我想我的问题是正确的!

关于java - 二维数组的构造函数只包含最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com