为了账号安全,请及时绑定邮箱和手机立即绑定

我不明白为什么我的代码的“再玩一次”部分不起作用

我不明白为什么我的代码的“再玩一次”部分不起作用

开心每一天1111 2023-09-13 10:55:32
我已经使用 java 几个星期了,想尝试制作我的第一个小游戏。我所拥有的一切都工作正常,直到我尝试添加再次播放功能。看起来它只是跳过了底部的一小部分代码,我不明白为什么。我尝试过移动代码的不同部分,但无法弄清楚为什么它不起作用。public static void main(String[] args) {    Scanner scan = new Scanner(System.in);    System.out.println("You have 10 tries to correctly guess a random number between 1 and 10. Good luck! \n"            + "After you have entered a number, press ENTER to see if you won.");    boolean play;       play = true;   do    {            int tries = 10, triesLeft = 0, triesUsed = 0;       String YorN;     do    {        System.out.print("\nEnter A Number: ");        int numInp = scan.nextInt();            int randomNumber = (int)(Math.random()*9) + 1;        System.out.println("The number was " + randomNumber);        if(numInp == randomNumber) {            System.out.println("\nYou Win! Great job.");            triesLeft = --tries;            triesUsed = 10 - triesLeft;            tries = -1;        } else {            System.out.println("Try Again...");            tries --;        }    }    while( tries > 0);    String playAgain = (" Feel free to play again soon!");    if(tries == 0) {        System.out.println("\nOut of tries :(   You lose loser  " + playAgain);    }    if(tries == -1) {    System.out.println("\nYou used " + triesUsed + " tries and had "            + triesLeft + " tries left! :)" + playAgain);    }    System.out.print("\nDo you want to play again? Y or N?");    YorN = scan.nextLine();    if (YorN == ("Y") || YorN == ("y"))    {        play = true;    }    else if (YorN == ("N") || YorN == ("n"))    {        play = false;    }    else {}   } while(play = true);   if (play = false){       System.out.println("\nGood Bye");    }}当我运行代码时,这个系统似乎没有做任何事情:YorN = scan.nextLine();    if (YorN == ("Y") || YorN == ("y"))    {        play = true;    }    else if (YorN == ("N") || YorN == ("n"))    {        play = false;    }    else {}这是我运行时看到的内容:你赢了!做得好。您已经尝试了 5 次,还剩 5 次尝试!:) 很快就可以再次玩了!你想再玩一次吗?是还是否?输入号码:它没有给我一个应该输入 y 或 n 的位置。如果有人知道为什么我会非常感谢你的帮助
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

nextInt() 或 next() 方法不读取 Enter。通常在数字之后您必须按 Enter 键,而上述方法尚未准备好。避免这种情况的排序方式是保留 1 个额外的 sc.nextLine() 方法调用。它将读取并丢弃输入。


scan.nextLine();

YorN = scan.nextLine();


    if (YorN == ("Y") || YorN == ("y"))

    {

        play = true;

    }

    else if (YorN == ("N") || YorN == ("n"))

    {

        play = false;

    }

    else {}


查看完整回答
反对 回复 2023-09-13
  • 1 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信