2015-12-27 68 views
0

我已經寫了一個基本的數字解析器,我相信它應該適用於雙精度和整數。然而,當被調用來解析一個數字時,它只能用於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 

回答

2

問題是這樣的語句:

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; 
+0

啊,我怎麼可能是這樣一個白癡。 PEMDAS Lol。謝謝。還沒有機會嘗試它,因爲我不在電腦上,但這就是爲什麼我沒有接受這個答案。我會盡快完成測試。 –

+0

我在最近幾分鐘內對我的答案進行了一些更正。我自己沒有測試過,但我認爲現在應該可以。 –

+0

好的再次感謝。有很多幫助:D我一直堅持了幾天。 –

1

嘗試改變這一行:

dnum = dnum + Character.getNumericValue(Lexer.fileContents[cIndex])/(10 * n); 

到:

dnum = dnum + (Character.getNumericValue(Lexer.fileContents[cIndex]) * 1.0)/(10 * n); 

在你現在的代碼,你將Character.getNumericValue(Lexer.fileContents[cIndex]),這一世S上int,由double - 這是始終等於0.0

+0

感謝您的快速響應。我非常感謝+1的幫助。不過,我會接受其他答案,因爲它有更多的細節,任何未來有這個問題的人可能會從中得到更多。 –

相關問題