2017-05-24 46 views
-8

我試圖編寫一個程序,它顯示所有可能的兩位數字並顯示這些數字的總和。獲取JAVA中數字的總和

例如:

10 - 1 + 0 = 1 
11 - 1 + 1 = 2 
12 - 1 + 2 = 3 
.. 
98 - 9 + 8 = 17 
99 - 9 + 9 = 18 

我用while循環來獲得正數是這樣的:

public static void main(String[] args){ 
    int count = 10; 

    while (count < 100) { 
     System.out.println("count:" + count); 
     count = count + 1;  
    } 

    System.out.print("Sum of Digits of " +sum);  
} 

我堅持與得到的這些數字的總和比如上例中。我在互聯網上閱讀了一些東西,但沒有運氣。

+0

您告訴我們期望的輸出,但不是您獲得的輸出。你有錯誤嗎?輸出錯誤? etc – jhhoff02

+0

試着將問題分解成更小的問題。在每個方程中,你需要三個數字。你已經擁有的第一個(櫃檯)。現在考慮如何根據計數器計算另外兩個數字。 –

+1

獲取個人數字不應該是一個問題,尤其是因爲您知道數字的最大大小(即最大2位數):嘗試'sum = count/10 + count%10;' – Thomas

回答

0

它的工作原理,如果你真的只有每個號碼兩個數字:A液

int count = 10; 
while (count <100){ 
    int first = count /10; 
    int second = count %10; 
    System.out.println(count + " - " + first +" + "+ second + " = " + (first+second)); 
    count = count + 1; 
} 

當學習Java,你應該,作爲第一步,瞭解基本的運營商,如/和%。這個安靜簡單的例子需要這兩個。

我儘量保持接近您的代碼以獲得預期的結果。 但是,還有其他解決方案(for-loop,count ++而不是count = count + 1 ...)