[英]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);
How do I make a switch statement repeat?如何使 switch 语句重复?
General answer: you put a loop around it.一般答案:你在它周围放一个循环。
In this case, the problem is that you have made a mistake in the loop.在这种情况下,问题是您在循环中犯了错误。
Specifically:具体来说:
} while (input = false);
is assigning false
to input
.将false
分配给input
。 The value of the assignment input = false
is false
... so your loop statement only executes the loop body once.赋值input = false
值为false
... 所以你的循环语句只执行一次循环体。
It should be this:应该是这样的:
} while (input == false);
Or better still 1 :或者更好的是1 :
} while (!input);
1 - It is better because when you use ==
to test a boolean, there is a risk that you will accidentally use =
instead ... with the consequences illustrated above! 1 - 更好,因为当您使用==
来测试布尔值时,您可能会不小心使用=
代替......后果如上所示! Note that in Java this problem only applies to boolean
tests.请注意,在 Java 中,此问题仅适用于boolean
测试。 For other types, x = y
will have a different type to x == y
and is sufficient for the mistake to result in a compilation error ... which is a GOOD thing, in this context.对于其他类型, x = y
将具有与x == y
不同的类型,并且足以使错误导致编译错误......在这种情况下,这是一件好事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.