[英]Java: while loop not working
我想在创建新游戏时检查用户输入,看看它是 y、n 还是两者都不是。
出于某种原因,它会一起跳过 while 循环,只输出“欢迎提问”。
import java.util.Scanner;
public class Questions {
public static final Scanner INPUT = new Scanner(System.in);
private boolean ans;
public Questions() {
while (ans = false) {
System.out.print("Do you want to start a new game (y/n)?: ");
String input = INPUT.nextLine();
if (input == "y"){
ans = true;
//some code
}
else if (input == "n"){
ans = true;
//some code
}
else {
System.out.println("Invalid input, Try again");
ans = false;
}
}//end while
}
public static void main(String[] args) {
Questions game = new Questions();
System.out.println("Welcome to Questions.");
}
while (ans = false) {
应该:
while (ans == false) {
=
用于赋值==
用于检查相等性
还使用.equals()
或.equalsIgnoreCase()
not ==
比较Strings
:
if (input == "y"){
应该:
if (input.equalsIgnoreCase("y")){
将私有布尔值 ans 更改为
private boolean ans = false;
或使用do while 循环
也使用== not =进行比较
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.