0

I am trying to read matrix data from a file and I'm not able to figure out what is wrong. This is the code that is not working:

        protected static double[][] getArrayFromFile(int new_rows, int new_cols,
            String file) 
        {
        double[][] A = new double[new_rows][new_cols]; 
        try {
            Scanner fileReader = new Scanner(new File(file));
            for (int i = 0; i < new_rows; i++)
                for (int j = 0; j < new_cols; j++)
                {
                if(fileReader.hasNextDouble())
                    A[i][j] = fileReader.nextDouble();
                else
                    {
                    System.out.println("missing numbers in file");
                    break;
                    }
                }

            fileReader.close();
            }
        catch (FileNotFoundException e1) {
            e1.printStackTrace();
            }

        return A;
        }

This method receives a file and the number of columns and rows to be read. It is not robust at all but it should work if you inform the parameters correctly. After testing it and printing the matrix, I get only zeros. I am already passing the absolute path to the data file and I'm pretty sure that the program is finding it due to the fact that when I pass a path that doesn't exist it shows an error message. When running debug I see that fileReader.hasNextDouble() is always returning false, so no number is getting read. Why is this happening? I have another method to read file from String that looks just like this and works perfectly.
Here it is:

protected double[][] getArrayFromString(int new_rows, int new_cols,
            String numbers)
        {
        Scanner stringReader = new Scanner(numbers);
        stringReader.useDelimiter("[^\\p{Alnum},\\.-]");

        double[][] A = new double[new_rows][new_cols]; 

        for (int i = 0; i < new_rows; i++)
        for (int j = 0; j < new_cols; j++)
            {
            if(stringReader.hasNextDouble())
                A[i][j] = stringReader.nextDouble();
            else
                {
                stringReader.close();
                throw new RuntimeException("\n"+""
                        + "missing numbers on string");
                }
            }

        stringReader.close();
        return A;
        }

I've been programming for quite a while with C and C++ and I've just started working with JAVA, so maybe there is something stupid that I'm doing. Can anyone see the mistake I'm making?


EDIT

This is the file I'm trying to read:

 23.0       0.84825
188.5       6.87425
269.0       10.9595
321.0       13.08725
4

1 回答 1

0

鉴于 getArrayFrom 文件会打开文件本身,因此 Locale 建议似乎更有可能不是您认为您在文件中的位置。

我建议在fileReader.useLocale(Locale.US);fileReader 的声明和初始化之后立即插入该行。根据解析数据的要求,这会将区域设置强制为小数点为“.”的区域。

或者,找出默认语言环境中的小数点并编辑文本文件以使用它。

于 2013-10-12T20:38:58.410 回答