java - 开关中的中断标签

标签 java switch-statement java-8 break

编辑: 感谢大家的帮助。我能够使用我在前几章中学到的技能和你的建议来让它工作。非常感谢!

我决定尝试通过创建一个简单的文本冒险来巩固我从 Java 中学到的东西:初学者指南。我即将开始涉及类和方法的第 4 章。前三章讨论了if、for、while、do-while、switch、简单的键盘交互和break/continue。

我计划在每一章之后回去编辑它,以使用我学到的新技能。我几乎没有触及表面,但遇到了问题。

// A basic, but hopefully, lengthy text adventure.

class TextAdventure
{
    public static void main(String args[])
    throws java.io.IOException
    {
        System.out.println("\t\t BASIC TEXT ADVENTURE");


        // variables I need, attributes, classes, character name, player's choice, gold
        int str = 0, inte = 0, chr = 0, con = 0, dex = 0, gold;
        char charName, choice;

        System.out.println("Welcome player! You are about to embark upon a quest in the form of a text adventure.");
        System.out.println("You will make choices, fight monsters, and seek treasure. Come back victorious and you");
        System.out.println("could quite possibly buy your way into nobility!");
        System.out.println();


caseChoice: {       
        System.out.println("Please select your class:");
        System.out.println("1. Warrior");
        System.out.println("2. Mage");
        System.out.println("3. Rogue");
        System.out.println("4. Archer");

        choice = (char) System.in.read(); // Get players choice of class



        switch(choice)
        {
        case '1': 
            System.out.println("You have chosen the Warrior class!");
            System.out.println("You're stats are as followed:");
            System.out.println("Str: 16");
            System.out.println("Int: 11");
            System.out.println("Chr: 14");
            System.out.println("Con: 15");
            System.out.println("Dex: 9");
            str = 16; 
            inte = 11;
            chr = 14;
            con = 15;
            dex = 9;
            break;

        case '2':
            System.out.println("You have chosen the Mage class!");
            System.out.println("You're stats are as followed:");
            System.out.println("Str: 16");
            System.out.println("Int: 11");
            System.out.println("Chr: 14");
            System.out.println("Con: 15");
            System.out.println("Dex: 9");
            str = 9; 
            inte = 16;
            chr = 14;
            con = 15;
            dex = 11;
            break;

        case '3':
            System.out.println("You have chosen the Rogue class!");
            System.out.println("You're stats are as followed:");
            System.out.println("Str: 16");
            System.out.println("Int: 11");
            System.out.println("Chr: 14");
            System.out.println("Con: 15");
            System.out.println("Dex: 9");
            str = 15; 
            inte = 11;
            chr = 14;
            con = 9;
            dex = 16;
            break;

        case '4':
            System.out.println("You have chosen the Archer class!");
            System.out.println("You're stats are as followed:");
            System.out.println("Str: 16");
            System.out.println("Int: 11");
            System.out.println("Chr: 14");
            System.out.println("Con: 15");
            System.out.println("Dex: 9");
            str = 9; 
            inte = 11;
            chr = 14;
            con = 15;
            dex = 16;
            break;

            default:
                System.out.println("Not a valid choice, please enter a digit 1-4");
                break caseChoice;

        }

}

    }
}

开关中默认语句的目的是将代码流带回类选择。我没有收到编译错误或运行时错误。当您选择 1、2、3 或 4 以外的任何内容时。它会说“不是有效的选择,请输入数字 1-4”,就像它假设的那样,但程序结束了。

我不允许在开关中使用这样的标签吗?或者它不起作用是因为它在技术上位于代码块之外?

最佳答案

我相信您在问题中描述的是某种goto 功能,而这不是 Java 中标签的工作方式。

Java 不幸的是 支持标签。这在 this article from Oracle 中有描述。 .

因此,基本上您可以使用标签进行循环,并且可以使用关键字 continuebreak 等来控制循环的流程。

以下示例说明了如何使用带有 break 关键字的循环。当调用 break 时,它会终止带标签的语句,即 someLabel 之后的语句。它不会返回到指定标签的位置执行。

someLabel:
    for (i = 0; i < 100; i++) {
        for (j = 0; j < 100; j++) {
            if (i % 20 == 0) {
                break someLabel;
            }
        }
    }

continue 关键字以相同的方式处理标签。当您调用例如continue someLabel; 外层循环将继续。

作为per this SO-question你也可以这样构造:

BlockSegment:
if (conditionIsTrue) {
    doSomeProcessing ();
    if (resultOfProcessingIsFalse()) break BlockSegment;
    otherwiseDoSomeMoreProcessing();
    // These lines get skipped if the break statement
    // above gets executed
}
// This is where you resume execution after the break
anotherStatement();

所以,如果您break 到您的switch 中的标签,基本上会发生什么,您将中断整个语句(而不是跳转到语句的开头)。

您可以通过运行以下程序进一步测试标签。如果您输入“退出”,它会中断 while 循环,否则它只会中断开关。

public static void main(String... args) {
    programLoop:
    {
        while (true) {
            Scanner scanner = new Scanner(System.in);
            final String input = scanner.next();
            switch (input) {
                case "quit":
                    break programLoop; // breaks the while-loop
                default:
                    break; // break the switch
            }
            System.out.println("After the switch");
        }
    }
}

就我个人而言,只有在非常特殊的情况下我才会推荐使用标签。我发现如果您重新排列代码以便不需要标签(例如通过将复杂的代码分解为更小的函数),代码会更容易理解。

关于java - 开关中的中断标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28003929/

相关文章:

java - coldFusion jvm垃圾收集不是

java - MultiDex 在 Android 4.4 中导致 java.lang.NoClassDefFoundError

java - Android 将可点击文本设置为从一个 fragment 转到另一个 fragment

c++ LNK2019错误,未解析的外部字符

logging - 使用 Stream API 记录排除结果的更好方法

Java 8 日期和时间时间字段

java - 使用 Junit 进行多步测试

java - 编写包含大量案例的开关案例代码的最佳设计模式是什么?

java - 存储在变量中与具有多种不同的方法

Java重播日志,诊断内存不足错误