输入后程序冻结?

时间:2012-05-31 04:33:08

标签: java loops input while-loop freeze

用户输入他们的选择后,程序似乎再次提供相同的选择,然后完全冻结。它只设置在那里给他们一次选择(我相信)然后按照下面的选择。相反,它似乎恢复到顶部,然后只是因为一些奇怪的原因冻结。尝试搞清楚一段时间,但无济于事。

public void init() //Initialize method {

    setSize(1000, 800); //Set size
    Container c = getContentPane();
    c.setBackground(Color.GREEN); //Set background
}    


public void paint(Graphics g)  {

    super.paint(g); //Start paint method
    g.setFont(new Font("Veranda", Font.PLAIN, 20));
    g.setColor(Color.BLACK);
    g.drawString("Hello", 250, 25); //top display message
    String number = JOptionPane.showInputDialog("Would you like a custom loop count or an infinite? 1. Custom 2. Infinite"); //test choice
    n = Integer.parseInt(number);

    while (n>0 || n<2)
    if (n==1) { 
            String number2 = JOptionPane.showInputDialog("How many times would you like to loop?");
            integer = Integer.parseInt(number2);
            while (integer>0)
                while (x < integer) {   
                    g.drawString("hi", 200, y); 
                    x+=1;
                    y = y+40; //test
                }//end while
    }//end if 
    else if (n==2)  {
        while (true); //im aware this is an endless loop. Can't find anything more stable for an endless one, so its just there for now..
    }//end if   
    else;
    g.drawString("Please pick a valid choice", 200, 200);               
}//end paint
}//end

1 个答案:

答案 0 :(得分:0)

这就是我所理解的

while (integer>0) {
    while (x < integer)
    {   
        g.drawString("hi", 200, y); 
        x+=1;
        y = y+40; //test
    }//end while
    integer --; // <-- This is missing
}
break; // <-- Also missing

当x =整数时,内部结束 但整数总是> 0 你必须在外循环结束时做integer -- 所以它可以在某个时候变为0

请使用适当的缩进...它有帮助

我编辑了代码...看看我把'整数 - '

放在哪里

尝试将您的while(n>0 || n<2)转换为if(n>0 && n<2)

尽量不要使用while代替if,这样可以减少混淆

为所有代码块添加括号{},更易于阅读,因此更容易调试,也许您只需这样就可以解决这个问题

也是最后;之后的else

相关问题