2015-02-11 33 views
-1

嗨,我是新来的,通常是编程新手。我的老师告诉我们试着用一个小数到双转换器。那么我试着这样做,并认为我在正确的方式,但不知何故代码只是继续运行,而不显示转换的数字。所以我认为它里面可能有一个无限循环,但作为一个新手程序员,我无法找到它。帮助将不胜感激。我想我得到了一个无限循环

下面是代码:

import javax.swing.*; 

public class dezimalZuDual { 
    public static void main(String[] args) { 
    int dezimalZahl = Integer.parseInt(JOptionPane.showInputDialog("Hier eine Dezimalzahl eingeben:")); 
    int neu = dezimalZahl; 
    String dualZahl = ""; 

    while(neu != 0) 
    { 
     neu = dezimalZahl/2; 
     String rest = Integer.toString(dezimalZahl - neu * 2); 
     dualZahl = rest + dualZahl; 

    } 
    JOptionPane.showMessageDialog(null, "Die Dezimalzahl " + dezimalZahl + " ist im Dualzahlensystem ausgedrückt: " + dualZahl + "."); 
} 
} 

的代码编译没有任何错误,我在最后一行的消息将只是从未被显示。

+6

尝试使用调试器 – ControlAltDel 2015-02-11 17:56:09

回答

7

这里的问题是,你在做neu = dezimalZahl/2;,它改变了neu,但你永远不会改变dezimalZahl

例如:

dezimalZahl = 10; 
neu = 10/2 // (which is 5); 
// rest of your code 

然后你检查neu != 0,因为它是5。然后你通过你的循环运行一遍,你做同样的事情是真实的,但dezimalZahl仍然是10!这意味着neu将始终为5,这意味着你永远不会离开循环。

1

的问题是,neu从未改变

while(neu != 0) 
    { 
     neu = dezimalZahl/2; 
     String rest = Integer.toString(dezimalZahl - neu * 2); 
     dualZahl = rest + dualZahl; 

     //you are not changing(decreasing) value of neu 
     //nor you are changing dezimalZahl which would affect neu value 
     //so while loop returns true everytime and goes on 
    } 
相关问题