[英]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.