【发布时间】:2023-12-04 17:38:01
【问题描述】:
编辑: 感谢大家的帮助。使用我在前几章中学到的技能和您的建议,我能够让它发挥作用。非常感谢!
我决定尝试通过创建一个简单的文本冒险来巩固我从 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;
}
}
}
}
switch 中默认语句的目的是将代码流带回类选择。我没有收到编译错误或运行时错误。当您选择除 1、2、3 或 4 之外的任何内容时。它说“不是一个有效的选择,请输入一个数字 1-4”,就像它假设的那样,但程序结束了。
我不能在开关中使用这样的标签吗?还是因为它在技术上超出了代码块而不起作用?
【问题讨论】:
-
不,这不是有效的 java 语法 - 你应该使用 while 循环 (
while (!validChoice) { switch () { ... } })
标签: java switch-statement java-8 break