我已经编写了一个基本的数字解析器,我相信它应该适用于 double 和整数。然而,当调用解析数字时,它仅适用于 int 类型,当数字是 double 时(它通过到达小数点知道),它只是停止解析。有人可以告诉我这段代码有什么问题吗:
(注意:解析器正在解析先前读入字符数组的文件中的数字。我知道文件的内容已正确读入数组,因为我打印了数组内容并且它包含正确的内容)
我的号码解析器功能:
NumReturn numberParser(int cIndex) { // current index of array where num is
// found
int num = 0;
double dnum;
// int[] result = new int[2];
while (Character.isDigit(Lexer.fileContents[cIndex]) == true) {
num = num * 10 + Character.getNumericValue(Lexer.fileContents[cIndex]);
System.out.println(num);
cIndex++;
if (cIndex >= Lexer.fileContents.length)
break;
}
try {
if (Lexer.fileContents[cIndex] == '.') {
dnum = (double) num;
int n = 1;
while (Character.isDigit(Lexer.fileContents[cIndex++]) == true) {
dnum = dnum + Character.getNumericValue(Lexer.fileContents[cIndex]) / (10 * n);
n++;
System.out.println(dnum);
cIndex++;
if (cIndex >= Lexer.fileContents.length)
break;
}
System.out.println("Double Value:" + dnum);
return new NumReturn(dnum, cIndex);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Int Value:" + num);
return new NumReturn(num, cIndex);
}
NumReturn 类://即使您可能不需要看到这个
package jsmash;
public class NumReturn {
int value;
double dvalue;
int pointerLocation;
NumReturn(int value, int pointerLocation) {
this.value = value;
this.pointerLocation = pointerLocation;
}
NumReturn(double dvalue, int pointerLocation) {
this.dvalue = value;
this.pointerLocation = pointerLocation;
}
}
测试用例:
323 --> parses correctly and prints 323
323.54 --> stops parsing after the decimal and prints 323.0
最佳答案
问题在于这个语句:
dnum = dnum + Character.getNumericValue(Lexer.fileContents[cIndex]) / (10 * n);
/
运算符具有更高的优先级,因此计算结果如下:
dnum = dnum + (Character.getNumericValue(Lexer.fileContents[cIndex]) / (10 * n));
/
运算符两边都是 int
类型,因此这是一个整数除法。您将 < 10 的数字除以 >= 10 的数字,因此整数除法截断时总是得到 0。您需要将至少一个操作数设为double
,然后它才会进行浮点除法。然而,这并不是你的问题的结束。您的代码除以 10, 20, 30, .... 您希望它除以 10, 100, 1000, .... 另外,您将 cIndex 前进两次:在 while 条件内,并在循环中再次前进。您应该只执行一次。
++cIndex; // Advance past the decimal point.
double n = 10;
while (Character.isDigit(Lexer.fileContents[cIndex])) {
dnum += Character.getNumericValue(Lexer.fileContents[cIndex]) / n;
n *= 10;
关于java - 为什么这个数字解析器不能正确解析 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34483035/