![](/img/trans.png)
[英]How do I repeat code for a certain case in a switch statement and not repeat it for others?
[英]How do I make a switch statement repeat?
canner Input = new Scanner(System.in);
int userNum;
int computerNum = (int) (0 + Math.random() * 3);
System.out.println("Let's play rock paper scissors.");
System.out.println("Choose rock paper or scissors");
boolean input = false;
String userInput = Input.nextLine();
do {
switch (userInput.toLowerCase().trim()) {
case "rock":
userNum = 0;
input = true;
break;
case "paper":
userNum = 1;
input = true;
break;
case "scissors:":
userNum = 2;
input = true;
break;
default:
System.out.println("Please retry and make sure spelling is correct");
input = false;
break;
}
} while (input = false);
如何使 switch 语句重复?
一般答案:你在它周围放一个循环。
在这种情况下,问题是您在循环中犯了错误。
具体来说:
} while (input = false);
将false
分配给input
。 赋值input = false
值为false
... 所以你的循环语句只执行一次循环体。
应该是这样的:
} while (input == false);
或者更好的是1 :
} while (!input);
1 - 更好,因为当您使用==
来测试布尔值时,您可能会不小心使用=
代替......后果如上所示! 请注意,在 Java 中,此问题仅适用于boolean
测试。 对于其他类型, x = y
将具有与x == y
不同的类型,并且足以使错误导致编译错误......在这种情况下,这是一件好事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.