2015-11-30 101 views
-3

我想在創建新遊戲時檢查用戶輸入,並查看它是否是y,n或不是。Java:While loop not working

由於某種原因,它跳過while循環,只輸出「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."); 

} 
+3

您已將您的ans初始化爲false – Nakib

+2

您不會將字符串與字符串== == – redFIVE

+1

可能的重複[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do -i-compare-strings-in-java) – redFIVE

回答

3
while (ans = false) { 

應該是:

while (ans == false) { 

=是分配==是檢查平等

而且Strings使用.equals().equalsIgnoreCase()比較不==

if (input == "y"){ 

應該是:

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

@redFIVE你的權利我沒有注意到第一次......我在答案中添加了這個。 – brso05

0

更改私人布爾答到

private boolean ans = false; 

或使用做while循環

而且比較使用==沒有=完成

+0

,除OP之外的字符串 – redFIVE