简体   繁体   English

如何退出包含开关的While循环-Java

[英]How to Exit a While loop containing a switch - Java

This is for an assignment for a computers class. 这是针对计算机类的作业。 This is going beyond what the teacher asked for, so I am not asking you people to do my school work for me. 这超出了老师的要求,所以我不是要你们为我做学校的工作。 What I am not able to understand is how to exit the switch and the while. 我不明白的是如何退出开关和一段时间。 I know that using break; 我知道使用中断; will exit the while loop, and using break; 将退出while循环,并使用break; will exit a switch. 将退出一个开关。 What I am looking for is some code that will exit a switch and a while loop at the same time. 我正在寻找的是一些将同时退出开关和while循环的代码。 What I could do is just use 我能做的就是用

if (upgrade == 1){
    // Do Stuff
}

if (upgrade == 2){
    // Do Stuff
}

if (upgrade == 3){
    // Do Stuff
}

if (upgrade == 4){
    // Do Stuff
}

if (upgrade == 0){
    break;    // Exit the while loop
}

However, the teacher does not want us to use that format, but instead use switches. 但是,老师不希望我们使用该格式,而是使用开关。 I also thought that I could just add the 我还以为我可以添加

if (upgrade == 0){
    Break;
}

To the bottom, but that still is not using a switch, and my teacher would not be happy with it. 言归正传,但这仍然没有使用开关,我的老师不会对此感到满意。 Is there any way to exit a swtich and a while loop at the same time? 有什么办法可以同时退出swtich和while循环吗?

This is what he wants the code to look like: 这是他希望代码看起来像的样子:

while (timesLeveled > 0){

    System.out.println("Upgrade Stats");

    upgrade = chooseUpgrade();    // retrieves the number for upgrade

    switch (upgrade){
    case 1: 
        // Do stuff if upgrade is 1
        break;


    case 2:
                    // Do stuff if upgrade is 2
        break;


    case 3: 
        // Do stuff if upgrade is 3
        break;

    case 4:
        // Do stuff if upgrade is 4
        break;


    case 0:

        break;

    }   // Closes off Switch

            timesLeveled--; // resets level counter

        }   // Closes off while (timesLeveled)

I would usually recommend against using a switch at all when you have the option, but if you have to stick with it, you probably want the break with label . 我通常建议不要在选择时完全不使用switch ,但是如果您必须坚持使用它,则可能希望使用label break

WhileLoop: while (timesLeveled > 0) {
    ...
    case n:
        // do stuff
        break WhileLoop;
    ...
}

Note that this usage usually means that your code needs more than one significant cleanup (Replace Conditional with Polymorphism, loop improvement, etc.). 请注意,这种用法通常意味着您的代码需要进行多次重要的清理(用多态替换条件,改善循环等)。

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

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