为什么双精度数不能从我的String []数组中正确解析?

时间:2015-12-30 20:07:00

标签: java arrays parsing double

我试图从单维String数组中解析double值。当我尝试这样做时,双打总是解析为0.0,而不是正确的值。为什么会这样?

代码:

解析器方法:(忽略整数解析器,给定整数时这个工作正常)

NumReturn numberParser(int cIndex) { // current index of array where num is
        NumReturn nri;
        NumReturn nrd;
        try {
        nri = new NumReturn(Integer.parseInt(Lexer.token[cIndex]), cIndex++, 'i');
        System.out.println(nri.value + " ");
        return nri;
        }
        catch (NumberFormatException intExcep) {

          }
        try {
        nrd = new NumReturn(Double.parseDouble((Lexer.token[cIndex])), cIndex++, 'd');
        System.out.println(nrd.dvalue + " ");
        return nrd;
        }
        catch (NumberFormatException doubExcep) {
            doubExcep.printStackTrace();
          }
        return null;


    }

NumReturn课程:

package jsmash;

public class NumReturn {
    int value;
    double dvalue;
    int pointerLocation;
    char type;
    NumReturn(int value, int pointerLocation, char type) {
        this.value = value;
        this.pointerLocation = pointerLocation;
        this.type = type;
    }
    NumReturn(double dvalue, int pointerLocation, char type) {
        this.dvalue = value;
        this.pointerLocation = pointerLocation;
        this.type = type;
    }
}

我想解析的字符串数组:

static String[] token = new String[100];
token[0] = "129.4"; // I call my parser on this element of the array
token[1] = "+";
token[2] = "332.78"; // I call my parser on this element of the array

1 个答案:

答案 0 :(得分:2)

在我看来,这里的问题是一个简单的错字。在第二个NumReturn构造函数(具有double参数的构造函数)中,您当前具有以下内容:

this.dvalue = value;

这会将this.dvalue分配给this.value的初始值,即0。它完全忽略构造函数参数。你真正想要的是这个:

this.dvalue = dvalue;
              ^