2011-09-28 52 views
1

我忙於爲學校製作一個表達樹,我已經構建了構建樹的部分,並且打印算術表達式的結果也起作用。
有這額外的部分來完成任務,我只是想做這個工作。額外的任務是讓程序能夠讀取表達式。
我很喜歡這個,但我不確定我是否將這個東西用一個好的方式放在int的末尾。我試圖解決的問題是當有這樣一個表達式...
(3 *(8-2))+(12/4)
...我如何得到12出來的因爲他們是兩個分開的字符的字符數組?我在代碼的其餘部分使用了一系列字符,但當然可以使用字符串來獲取這兩個字符。如何將數字放在int(不是summming)的末尾?

我就是這麼做的:

// if the next character is a digit... 
if (Character.isDigit(expression[i])) { 
    // ... make local variables 'nextNumber'... 
    int nextNumber = 0; 
    // ... and 'a' which already contains this first digit... 
    String a = Character.toString(expression[i]); 
    // ... so when we check for the next character... 
    for (int k = i+1; k < expression.length; k++) { 
     // ... wether it is a digit,... 
     if (Character.isDigit(expression[k])) { 
      // ... we can add that digit to 'a',... 
      a = a + Character.toString(expression[k]); 
     } 
     // ... and if it is not a digit... 
     else if (!Character.isDigit(expression[k])) { 
      // ... we will exit the for loop. 
      break; 
     } 
    } 
    // now we have to change the String to an integer... 
    nextNumber = Integer.getInteger(a); 
    // ... and then we are sure we have the whole number as it was ment to be 
    // in the given expression 
    return new ET(nextNumber); 
} 

但似乎如此草率。我在谷歌搜索了很長時間,我發現的只是這種方式,但我無法想象有沒有更容易或至少沒有馬虎的方式。你們是否知道更好的方法,還是這條路要走?

我構建的解決方案是解決表達式樹問題的一種相對簡單的方法,我可以更加努力地工作,但我不想花費比需要的更多的時間,只要我可以向老師展示我明白了這些教訓。它的課程是Algorithmics,所以它並不是真的關於學習Java,我的意思是我沒有要求解決老師要求我解決的問題。

預先感謝您!

回答

2

可以建立由數字(僞碼)的數量位:

number = 0 
for each digit { 
    number = number * 10 + value_of(digit) 
} 

這將產生作爲number數字串(從左至右)的鹼值10

在你的情況下:digits = (1,2)

number = 0 
number = number * 10 + 1 // <= number = 0*10+1=1 
number = number * 10 + 2 // <= number = 1*10+2=12  
+0

我認爲這很清楚,但爲什麼'* 10'? '10點'是什麼意思? – Peter

+0

因爲通常我們在十進制數字系統中編寫數字(也稱爲base-10位置表示法) – Howard

+0

ahh我現在明白了,你的意思是我從 'number = 0' 開始,當我想給這個數字加1時, 0實際上向左移動,1在「開始」處被添加,並且當我想要添加2時,0和1將移動到左側並且2被添加。 'number = 0 // <= ____ 0' 'number = number * 10 + 1 // <= ___0_ + 1 - > ___ 01' 'number = number * 10 + 2 // <= __01_ + 2 - > __012' 'print(number); // <=輸出:12' – Peter

相關問題