我不了解while循环

时间:2015-01-27 09:34:12

标签: java loops while-loop

我是Java新手,我不太了解while循环。我想说'如果你不想选择Warrior课程,那就回到字符选择框。

while (chooseCharacter = true){

        String[] Character= {"Kitty", "Archer","Tank","Battlemage","Warrior"};
        int characterSelect = JOptionPane.showOptionDialog (null, "Choose your class", "Class Selection", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, Character, "Warrior");

        if(characterSelect == 4){
            JOptionPane.showMessageDialog(null, "Warrior" + "\n" + "Attack 1: Slash" + "\n" + "10 Damage :: 98% Accuracy" + "\n" + "Attack 2: Spin Attack" + "\n" +  "25 Damage :: 67% Accuracy");
            String[] warriorChar= {"No", "Yes"};
            int warrior = JOptionPane.showOptionDialog(null, "Would you like to choose Warrior as your class?", "Choose this class?", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, warriorChar, "No");
            if(warrior == 0){
                chooseCharacter = true;
            }
            if(warrior == 1){
                chooseCharacter = false;
            }
        }

2 个答案:

答案 0 :(得分:5)

while(chooseCharacter = true)
                      ↑ 

你要分配,而不是比较。你应该写:

while(chooseCharacter)

在Java中,赋值的表达式返回赋值的值,因此您的循环等效于while(true)

请注意,建议您编写

while(someBoolean)

而不是

while(someBoolean == true/false)

它可以保护你免受你所做的那样的错误,也可以用逻辑的方式思考它,如果你写if(something == true)就像问“如果值是真的那样......是真的”。

答案 1 :(得分:2)

使用

while (chooseCharacter == true){
}

while (chooseCharacter){

}

==是用于比较的运算符,=用于分配