我想在創建新遊戲時檢查用戶輸入,並查看它是否是y,n或不是。Java:While loop not working
由於某種原因,它跳過while循環,只輸出「Welcome to Questions」。
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.");
}
您已將您的ans初始化爲false – Nakib
您不會將字符串與字符串== == – redFIVE
可能的重複[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do -i-compare-strings-in-java) – redFIVE