【发布时间】:2016-03-04 14:26:32
【问题描述】:
我想在创建新游戏时检查用户输入,看看它是 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.");
}
【问题讨论】:
-
你已经将你的 ans 初始化为 false
-
你不要用
==比较字符串 -
@redFIVE 不是重复的,因为这是一个问题,但还有另一个问题需要先解决……请参阅我的答案。
-
@brso05 好吧,它肯定会成为下一个 Java 101,它会被问到零研究问题......
标签: java loops if-statement input while-loop