简体   繁体   中英

Java: while loop not working

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.");

}
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")){

Change private boolean ans to

private boolean ans = false;

or use do while loop

Also comparison is done using == not =

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM