为什么双打不能从我的 String[] 数组中正确解析?
Why do doubles not correctly parse from my String[] array?
我正在尝试从一维字符串数组中解析双精度值。当我尝试这样做时,双打总是解析为 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 Class:
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
在我看来,这里的问题只是一个简单的错字。在第二个 NumReturn
构造函数(带有双参数的构造函数)中,您当前具有以下内容:
this.dvalue = value;
这会将 this.dvalue
赋给 this.value
的初始值,即 0。它完全忽略了构造函数参数。你真正想要的是:
this.dvalue = dvalue;
^
我正在尝试从一维字符串数组中解析双精度值。当我尝试这样做时,双打总是解析为 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 Class:
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
在我看来,这里的问题只是一个简单的错字。在第二个 NumReturn
构造函数(带有双参数的构造函数)中,您当前具有以下内容:
this.dvalue = value;
这会将 this.dvalue
赋给 this.value
的初始值,即 0。它完全忽略了构造函数参数。你真正想要的是:
this.dvalue = dvalue;
^