简体   繁体   English

while循环不执行else语句并重复循环

[英]while loop does not preform else statement and repeat loop

When compiled upon not entering the right selection it doesnt display to re-enter or repeat the loop 在未输入正确选择的情况下进行编译时,不会显示以重新输入或重复循环

int counterA = 0;
while (counterA < 0) {
    if (conversionSelection.equalsIgnoreCase("binary"))
            counterA++;
    if (conversionSelection.equalsIgnoreCase("octal"))
            counterA++;
    else System.out.println("Error. Please enter weither to convert the Hex to Octal or Binary:");
        conversionSelection = keyboard.nextLine();
    }

The loop should not execute at all since the condition fails right from the get-go. 循环根本不应该执行,因为条件一开始就失败了。

There is also a dangling else statement. 还有一个悬而未决的声明。 So you need to have an else-if for your second if statement if you want the else to properly execute. 因此,如果您希望else正确执行,则需要在第二个if语句中添加else-if。 While it may not currently produce errors, it is an important skill to prevent dangling 'else's'. 尽管它目前可能不会产生错误,但是它是防止悬空“ else”的一项重要技能。

Your code will never enter the while loop since counterA = 0 and the while loop condition is for it to be < 0 . 因为counterA = 0并且while循环条件是< 0 ,所以您的代码将永远不会进入while循环。 You want counterA to be less than zero, or the condition to include counterA 's value in its set (eg while (counterA <= 0) ). 您希望counterA小于零,或希望在其集合中包含counterA的值的条件(例如, while (counterA <= 0) )。

因为0不小于0,所以此循环永远不会开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM