所以我已经使用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的位置。如果有人知道为什么我会非常感谢您的帮助
答案 0 :(得分:0)
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 {}