2013-10-22 89 views
0

我寫了一個PROGRAMM得到了許多的交叉總和:分割成數幾個號碼

所以,當我在3457例如鍵入它應該輸出3 + 4 + 5 + 7,但不知何故,我LOGIK不會工作。當我輸入68768例如我得到6 + 0 + 7.但是,當我輸入97999我得到正確的輸出9 + 7 + 9.我知道我可以用不同的方法輕鬆完成這項任務,但我試圖使用循環。這裏是我的代碼:並感謝所有

import Prog1Tools.IOTools; 

public class Aufgabe { 
    public static void main(String[] args){ 
     System.out.print("Please type in a number: "); 
     int zahl = IOTools.readInteger(); 

     int ten_thousand = 0; 
     int thousand = 0; 
     int hundret = 0; 


     for(int i = 0; i < 10; i++){ 
      if((zahl/10000) == i){ 
       ten_thousand = i; 
       zahl = zahl - (ten_thousand * 10000); 
      } 

      for(int f = 0; f < 10; f++){ 
       if((zahl/1000) == f){ 
        thousand = f; 
        zahl = zahl - (thousand * 1000); 
       } 

       for(int z = 0; z < 10; z++){ 
        if((zahl/100) == z){ 
         hundret = z; 
        } 
       } 


      } 
     } 
      System.out.println(ten_thousand + " + " + thousand + " + " + hundret); 
    } 
} 
+2

'9999'應該輸出什麼?你想忽略重複的數字嗎? –

+1

@JohnSmith爲什麼不把它轉換爲字符串並遍歷字符串的每個字符? – Apostolos

+1

你怎麼表達交叉?不明白爲什麼97999我得到正確的輸出9 + 7 + 9是正確的。是不同數字的總和? –

回答

1

你提出的代碼的問題是你嵌套了內部循環。相反,在開始下一個循環之前,您應該完成每個循環的迭代。

目前與68768發生了什麼事情是當外循環達到i = 6時,ten_thousand項設置爲6,內循環繼續計算「千」和「100」項 - 並且確實如你所期望的那樣設置了這些值(並且將zahl等於768--注意你不會在數百個階段減少zahl)

但是然後外層循環繼續循環,這次是i = 7。隨着zahl = 768,zahl/1000 = 0',所以'千'期限被設置爲0.在zahl = 768的情況下,百項總是被重置爲7。

97999的工作原理是因爲在'i'循環的最後一次循環中設置了千分之一項,所以永遠不會重置。

補救措施是不嵌套內循環 - 它會表現更好!

3

這是你想要的嗎?

String s = Integer.toString(zahl); 
for (int i = 0; i < s.length() - 1; i++) { 
    System.out.println(s.charAt(i) + " + "); 
} 
System.out.println(s.charAt(s.length()-1); 
1

你應該做這樣的事情

input = 56789; 

int sum = 0; 

int remainder = input % 10 // = 9; 
sum += remainder // now sum is sum + remainder 
input /= 10; // this makes the input 5678 

... 
// repeat the process 

要循環播放,使用while循環,而不是一個for循環。這是什麼時候使用while循環的一個很好的例子。如果這是一門課程,它將顯示您瞭解何時使用while循環:迭代次數未知,但基於條件。

int sum = 0; 
while (input/10 != 0) { 
    int remainder = input % 10; 
    sum += remainder; 
    input /= 10; 
} 
// this is all you really need 
0

您的示例有點複雜。要提取tenthousand,一千幾百,你可以簡單地這樣做:

private void testFunction(int zahl) { 
    int tenThousand = (zahl/10000) % 10; 
    int thousand = (zahl/1000) % 10; 
    int hundred = (zahl/100) % 10; 
    System.out.println(tenThousand + "+" + thousand + "+" + hundred); 
} 

位儘可能多的開發者報告,你應該通過字符轉換爲字符串和工藝特點。