[英]Switch case doesn't print to the console?
public static void startGame(){
//int stone = 0, diamond = 0, iron = 0, gold = 0;
StringBuffer blockys = new StringBuffer("\uD83E\uDDCD ▯▯▯▯▯▯▯▯▯");
Scanner input = new Scanner(System.in);
System.out.println("\uD83E\uDDCD " + "▯▯▯▯▯▯▯▯▯" + "\n");
String user = input.next();
boolean game = true;
while(game) {
switch (user) {
//Code
case "M":
System.out.println(mine(blockys));
user = input.next();
break;
}
}
public static StringBuffer mine(StringBuffer blockys){
addOre(blockys);
blockys.delete(2, 3);
int randBlock = (int) (Math.random() * 101) + 0;
//Code
else{
//add bomb 5% chance
blockys.append("\uD83E\uDDE8");
}
return blockys;
}
public static void addOre(StringBuffer blockys){
String str = blockys.substring(2, 3);
switch(str){
//Code
case "\uD83E\uDDE8":
System.out.println("You mined a bomb! BOOOOOOOM! You died!");
System.exit(0);
break;
}
}
在我的方法 addOre 中,当它到达 case "\?\?" 时,它不会打印到控制台,也不会终止程序。 当遇到这种情况时,它会完全忽略它并继续程序。 我曾尝试将其设置为失败的默认值,并在案例中尝试了不同的变量,但它从未打印任何内容。 如何修复它以便它打印并在之后终止?
它是一个“长度”问题。
考虑以下代码:
public static void main(String[] args) {
System.out.println("Hello".substring(2, 3).length());
System.out.println("\uD83E\uDDE8".length());
}
将输出:
1
2
那么问题是什么?
当您使用子字符串时,您将始终返回长度为 1 的字符串。
而在另一端,在您的 switch 案例中,您正在尝试测试长度为 2 的字符串。
1 != 2: 条件从未满足
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.