2015-11-16 198 views
0

我無法弄清楚爲什麼我的循環不會繼續。每次運行程序時,它只執行一次循環迭代。這while循環似乎不循環 - 循環中只有數學

我正在實施基於數學家劉易斯卡羅爾的算法,您從輸入號碼中刪除最後一位數字,並從剩餘數字形成的數字中減去它。例如,如果我輸入數字48070輸出是

48070 
4807 

它停在那裏,而不是繼續。

// The "Divisible_Dianik" class. 
import java.awt.*; 

public class Divisible_Dianik 
{ 

    public static void main (String[] args) 
    { 
     int userinput = 1; 
     int lastint; 
     int firstpart; 
     int output = 1; 

     while (output != 0) 
     { 
      userinput = In.getInt(); 
      lastint = userinput % 10; 
      firstpart = userinput/10; 
      output = firstpart - lastint; 
      System.out.println (output); 
      userinput = output; 
     } 

    } // main method 
} // Divisible_Dianik class 
+1

您是否嘗試過使用print語句或調試器進行調試? –

+0

這就是我們在學校使用的輸入整數的用戶。 –

+0

然後它是'In.class'你擁有的不是嗎?或者你有'In.java'?如果是這樣,在這裏粘貼代碼 – Frakcool

回答

5

我要去假設In.getInt()是某種抽象從用戶獲得基於終端的反饋。它很容易被這種取代:

Scanner scan = new Scanner(System.in); 
// in the loop 
userinput = scan.nextInt(); 
scan.nextLine(); 

如果是這樣的話,你不循環的原因是由於每次這種阻塞輸入。你想要做的是將輸入的請求移到循環的之外。

int lastint; 
int firstpart; 
int output = 1; 
Scanner scan = new Scanner(System.in); 
int userinput = scan.nextInt(); 
while (output != 0) { 
    lastint = userinput % 10; 
    firstpart = userinput/10; 
    output = firstpart - lastint; 
    System.out.println(output); 
    userinput = output; 
} 
+0

你張貼在我的中間寫作完全一樣.. – jso

+0

感謝它的工作!它甚至工作,如果我只是移動In.getInt ouside循環:) –

+1

@jso,這經常發生在SO上。 –