问题
I want to check the users input when a new game is created, and see if it is y, n, or neither.
For some reason it skips the while loop all together and just outputs "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.");
}
回答1:
while (ans = false) {
Should be:
while (ans == false) {
=
is for assignment ==
is for checking equality
Also Strings
are compared using .equals()
or .equalsIgnoreCase()
not ==
:
if (input == "y"){
Should be:
if (input.equalsIgnoreCase("y")){
回答2:
Change private boolean ans to
private boolean ans = false;
or use do while loop
Also comparison is done using == not =
来源:https://stackoverflow.com/questions/34007291/java-while-loop-not-working