我已經寫了一個基本的數字解析器,我相信它應該適用於雙精度和整數。然而,當被調用來解析一個數字時,它只能用於int類型,當數字是一個double(它通過達到一個小數點來知道)時,它只是停止解析。有人可以告訴我這個代碼有什麼問題:爲什麼這個數字解析器不能正確解析雙打?
(注意:解析器是從先前讀入char數組的文件中解析數字,我知道文件的內容被正確地讀入到數組中因爲我打印數組的內容,它包含正確的內容)
我的號碼分析器功能:
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
啊,我怎麼可能是這樣一個白癡。 PEMDAS Lol。謝謝。還沒有機會嘗試它,因爲我不在電腦上,但這就是爲什麼我沒有接受這個答案。我會盡快完成測試。 –
我在最近幾分鐘內對我的答案進行了一些更正。我自己沒有測試過,但我認爲現在應該可以。 –
好的再次感謝。有很多幫助:D我一直堅持了幾天。 –