类中的数字格式异常

时间:2017-02-09 17:30:01

标签: java

我认为我的问题是一个愚蠢的,语法上的问题,但现在就是这样。我正在编写一个带有CSV文件的程序,该文件是3行4列数字。我在运行时将该文件作为参数使用,然后在换行符(\ n)处拆分,然后在逗号分隔符处拆分。然后我将其存储到" 2D阵列"字符串类型。然后,我将每个值,解析加倍,并填充第二个" 2D数组"但这一次加倍。一切都很好。

我的问题是当我尝试接受所有代码并将其放入自己的课程时。我在main中添加了一个构造函数,在类中我复制并粘贴了以前工作的代码。但是现在当从string解析为double时,从第4个元素到第5个元素时,我得到NumberFormatException。在主要编码时,完全相同的代码有效。

我认为我对课程的了解是我的问题。

这是我正在上课的课程:

import java.lang.*;

public class Assignment1{
    public static void main(String[] args){

//  DecimalFormat df = new DecimalFormat("#.##");   

        //Make sure the user passed the command line argument - and nothing else
        if (args.length != 1){
            System.out.println("Assignment1 takes exactly one command-line argument.");
            System.out.println("Usage: java Assignment1 some_file.csv");
            System.exit(0);
        }

        String csvFileName = args[0];

        //Instantiate my custom file reader
    CSVReader fileReader = new CSVReader();

        //Read the file into a string
        String text = fileReader.readFile(csvFileName);
    DataMatrix matrix = new DataMatrix(text);  

}//end of main
}//end of class

这是我的主要内容(忽略评论,在我复制/粘贴内容时使用它们):

Files contents:
1,2,3,4
3,4,1,0
2,3,4,2

Original String:
1
2
3
4
3
4
1
0
2
3
4
2

Converted to double:
1.0
2.0
3.0
Exception in thread "main" java.lang.NumberFormatException: For input string: "4 3"

at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1250)
at java.lang.Double.parseDouble(Double.java:540)
at DataMatrix.<init>(DataMatrix.java:30)
at Assignment1.main(Assignment1.java:22)

编辑:这是我的输出:

isPersistant

2 个答案:

答案 0 :(得分:0)

构造函数中的局部变量dMatrix隐藏属性dMatrix

只需在构造函数代码中double[][] dMatrix = new double[sMatrix.length][];更改dMatrix = new double[sMatrix.length][];

答案 1 :(得分:0)

我担心你当前版本的程序中有太多不太合适的东西。我会尽力简化它。你可以将它与你的比较并了解错误:

import java.lang.*;

public class DataMatrix {

    public DataMatrix(String text) {
        //Replace the new line character (\n or \\r or \r\n) with a comma and split based on comma.
        String[] numbers = text.replaceAll("\r?\n|\r", ",").split(",");
        for(int i=0; i<numbers.length; i++)
           System.out.println(Double.parseDouble(numbers[i]));

    }
}