简体   繁体   English

Java:while循环不起作用

[英]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.我想在创建新游戏时检查用户输入,看看它是 y、n 还是两者都不是。

For some reason it skips the while loop all together and just outputs "Welcome to Questions."出于某种原因,它会一起跳过 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) {

Should be:应该:

while (ans == false) {

= is for assignment == is for checking equality =用于赋值==用于检查相等性

Also Strings are compared using .equals() or .equalsIgnoreCase() not == :还使用.equals().equalsIgnoreCase() not ==比较Strings

if (input == "y"){

Should be:应该:

if (input.equalsIgnoreCase("y")){

Change private boolean ans to将私有布尔值 ans 更改为

private boolean ans = false;

or use do while loop或使用do while 循环

Also comparison is done using == not =也使用== not =进行比较

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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