Java while循环永远不会进入循环

use*_*003 0 java while-loop

我正在用java写一个视频扑克,我需要问玩家是否要从他们手中取出任何牌.我为此写了一个while循环,但它没有像现在这样的方式工作.如果有人能把我送到正确的方向,我会很感激 - 我还是java的新手......谢谢.(这counter是因为玩家不会删除超过5张牌)

    String response = "y";
    int counter = 0;
    System.out.println("Remove any cards?");
    System.out.println("Enter y for 'yes' and n for 'no'");
    response = input.nextLine();
    while((response != "n") && (counter < 5))
    {

        System.out.println("Enter the number of a card to be removed (1-5)");
        int l = input.nextInt();
        p.removeCard(p.getHand().get(l-1));
        p.addCard(cards.deal());
        cards.incrementTop();
        counter ++;
        System.out.println("Card removed. More? Type 'yes' or 'no'");
        String answer = input.nextLine();
        if (answer == "no")
            {
                response = "n";
            }       
    }  
Run Code Online (Sandbox Code Playgroud)

Mar*_*rno 5

您无法使用!=或比较字符串==.

使用 .equals()

while(!("n".equals(response)) && (counter < 5))
Run Code Online (Sandbox Code Playgroud)

这里也一样

if (answer == "no")
Run Code Online (Sandbox Code Playgroud)

其他需要改进的地方

  • 用户可以在第一次写"否"以及它现在如何完成它无法正常工作
    • 你要求用户写"不",但检查"n"
  • N怎么样?Y'
  • 怎么样?没有?(提示:搜索.equalsIgnoreCase())

另一个暗示:使用布尔变量yes/no,更好更容易:)