如果输入了超出选项的内容,如何重复if或switch语句? [英] How to repeat an if or switch statement if something out of option is entered?

查看:359
本文介绍了如果输入了超出选项的内容,如何重复if或switch语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数情况下该重复,但是由于这个问题太长且太复杂,我真诚地不知道如何搜索该问题.不好意思!

This will mostly get duplicated but I sincerely don't know how to search this question since it is too long and complicated. Sorry in advance!

回到问题所在,假设我从用户那里获得了Scanner类的输入.想象一下,扫描仪已导入并且一切都已设置.

Back to the problem, let's say I take an input from the user with the Scanner class. Imagine that Scanner is imported and everything is set.

Scanner scan = new Scanner();
String input = scan.nextLine();
switch( input) {
    case "attack":
       System.out.println( "You attacked the enemy!");
       break;

    case "defend":
       System.out.println( "You blocked the enemy!");
       break;

    default:
       System.out.println( "This is not an option!");
       // somehow repeat the process until one of the case options are 
       // entered.
}

在执行案件之前,如何重复请求输入并检查案件的过程?

How do I repeat this process of asking for an input and checking for a case until a case is executed?

我可以将其放在while循环中,当输入case选项时,我可以退出while循环,但是当我有很多switch/if语句都需要可靠输入的时候,这似乎太多了.以便处理其余代码. 有没有办法在Java中更有效地做到这一点?

I could put this inside a while loop and when a case option is entered I could exit out of the while loop, but that just seems too much code when I have plenty of switch/if statements that both require a solid input in order to process the rest of the code. Is there a way to do this more efficiently in Java?

推荐答案

Scanner scan = new Scanner(System.in);
loop:
while (true) {
    String input = scan.nextLine();
    switch (input) {
        case "attack":
            System.out.println("You attacked the enemy!");
            break loop;

        case "defend":
            System.out.println("You blocked the enemy!");
            break loop;

        default:
            System.out.println("This is not an option!");
            break;
    }
}

您可能知道,

while (true)造成无限循环.在switch语句中,如果输入是攻击或防御,我们将跳出循环.如果两者都不是,我们只会跳出switch语句.

while (true) makes an infinite loop as you may know. In the switch statement, if the input is attack or defend, we break out of the loop. If it is neither of those, we only break out of the switch statement.

while循环用loop:标签标记.这样我们就可以告诉它break loop;脱离循环.另一方面,break仅超出switch语句.

The while loop is marked with the loop: label. This is so that we can tell it to break loop; to break out of the loop. On the other hand break only breaks out of the switch statement.

这篇关于如果输入了超出选项的内容,如何重复if或switch语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆