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

标签 java arrays file-upload multidimensional-array

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

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/

相关文章:

arrays - 使用Python计算行是否包含这个和那个,然后制作结果的热图(?不确定这是否是正确的术语)

MySQL 在数据库数组字段中搜索值(整数或字符串)

java - 创建自定义异常

java - Applet 中的图像未显示在网页中

java - 需要读入 ArrayList 并将正数和负数分开

file-upload - 如何使用 Talend tREST 上传文件?

java - 即 11 : Error while sending Multipart Form Data request: Stream ended unexpectedly

php - 交响乐 2 |修改具有文件(图片)字段的对象时出现表单异常

java - 从 rgb 像素值创建缓冲图像

java - libgdx 使鼠标在几秒钟不活动后重新出现的问题