Java: while loop not working

我的梦境 提交于 2020-01-30 13:26:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!