0

我正在製作一個遊戲人生計劃,它的早期階段。當我運行程序並進入「你想做什麼...」並輸入「y」時,它會轉到else,打印我的測試語句test3,並結束程序。我忽略了什麼?爲什麼如果陳述不符合我的要求呢?

public static void main(String[] args) { 

    Scanner kb = new Scanner(System.in); 

    String userInput = ""; 
    char[][] initialGrid = new char[25][75]; 
    char[][] world = makeInitialGrid(kb, userInput, initialGrid); 
    printGrid(world); 
    userInput = "y"; 
    while (userInput == "y"){ 
     System.out.println("Do you want to make a new generation? (y) yes (n) no"); 
     userInput = kb.nextLine(); 
     System.out.println(userInput); 
     if (userInput == "y"){ 
      System.out.println("test1"); 
      int numOfNeighbors = findNeighbors(world, 6, 2); 
      System.out.println("test2"); 
      System.out.println(numOfNeighbors); 
      //makeNewGeneration(world); 
     } else { 
      System.out.println("test3"); 
      break; 

     } 
    } 
    kb.close(); 

回答

2

對於Java字符串比較,你需要使用String#equals,不==。改爲嘗試if (userInput.equals("y")) { ...

+0

哦,呃......當然。非常感謝你。 – 2014-11-04 03:31:49

+0

沒問題!如果這解決了您的問題,請記住接受答案。 – Gian 2014-11-04 03:32:47