使用do while循环在java中循环代码时出现问题

gopyfrb3  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(226)

这个问题在这里已经有答案了

如何比较java中的字符串(23个答案)
一小时前关门了。
另一天另一个问题。
我在试着创造一个有回合的文字游戏。在当前回合结束后会添加其他回合,提示用户回答是否要玩另一回合。我试着使用do while循环,这样在回答问题时,如果他们回答yes,他们就去玩另一轮,如果他们回答no,他们就结束游戏,继续代码。唉,不管答案是什么,代码都在重复自己,导致了无限循环。感觉我被困在我最不喜欢的一集布菲。我对重复循环非常缺乏经验。我在课堂上见过,但我自己从来没用过
下面是循环中的代码(为了简洁起见,我们删掉了对话)。示例化类的示例称为game。布尔值最初设置为true

do {
    //Computations 1
    Game.computeletters(); //Getting random letters from Instantiable class

    letters = Game.getLets(); //Retrieving the random Letters
    JOptionPane.showMessageDialog(null, "blah");
    System.out.println(letters);
    System.out.println("blah");

    //Computations 2  //To allow the points to be shown before entering a word in the rounds after the first
    Game.computepoints(); //Grabbing the points totals
    p1RS = Game.getP1RS();
    p2RS = Game.getP2RS();
    p1S = Game.getP1S();
    p2S = Game.getP2S();

    //Input
    p1Answer = JOptionPane.showInputDialog("Player 1 answer");
    p2Answer = JOptionPane.showInputDialog("Player 2 answer");

    //Validation
    if (p1Answer.matches("^[a-zA-Z]*$") && (legalWords.contains(p1Answer))) {
        Game.setP1Answer(p1Answer);
        System.out.println("Player 1's answer is :" + p1Answer);
        Game.computepoints(); //Grabbing the points totals
        p1RS = Game.getP1RS();
    } else {
        JOptionPane.showMessageDialog(null, "blah");
        System.out.println("Player 1's answer is invalid");
    }

    if (p2Answer.matches("^[a-zA-Z]*$") && (legalWords.contains(p2Answer))) {
        Game.setP2Answer(p1Answer);
        System.out.println("Player 1's answer is :" + p2Answer);
    } else {
        JOptionPane.showMessageDialog(null, "blah");
        System.out.println("blah bad answer");
    }

    confirm = JOptionPane.showInputDialog("Would you like to play another round? Please enter 'y' to continue or 'n' to end the game with the current scores");
    if (confirm == "y") {
        rounds = true;
        roundNumber = roundNumber + 1;

    } else if (confirm == "n") {
        rounds = false;
    }
} while (rounds = true);

我一直在尝试在多个点开槽闯入,但似乎不起作用。代码循环正确,但没有正确退出。我使用的是错误的循环还是正确的循环?
任何帮助都将不胜感激

fquxozlt

fquxozlt1#

if(confirm == "y"){
    rounds = true;
    roundNumber = roundNumber + 1;

}
else if(confirm == "n"){
    rounds = false;
}

问题就在这里。您正在使用==运算符比较字符串,这不起作用。==运算符检查比较的对象是否具有相同的引用,而不是它们的存储值是否相等。如果要检查字符串或其他对象的相等性,请使用equals()方法:

if(confirm.equals("n")){

或:

if("n".equals(confirm)){

相关问题