我正在编写一个简单的猜谜游戏程序,用户将输入一个数字来尝试猜测一个随机生成的数字。
如果他们的号码正确,我想给他们选择再次玩的机会。
这是我的代码:
public class GuessingGame {
private Random num = new Random();
private int answer = num.nextInt(10);
private int guess;
private String playAgain;
public void inputGuess(){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
Scanner input = new Scanner(System.in);
guess = input.nextInt();
do{
if (guess < 1 || guess > 10){
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}else if (guess > answer){
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}else if (guess < answer){
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
}while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = input.nextLine();
if(playAgain == "Y" || playAgain == "y"){
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
}
}
}
游戏进行完毕,但是提示用户再次玩游戏时,什么都没有发生?
有什么建议?
这是完整的代码,完全可以使用并经过测试。
public static void main(String[] args)
{
String playAgain = "";
Scanner scan = new Scanner(System.in);
do
{
ClassName.inputGuess();
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
playAgain = scan.nextLine();
}
while(playAgain.equalsIgnoreCase("Y"));
System.out.println("Thanks for playing!");
}
public void inputGuess()
{
Random num = new Random();
int answer = num.nextInt(10)+1;
Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10 as your first guess: ");
guess = input.nextInt();
do
{
if (guess < 1 || guess > 10)
{
System.out.println("That is not a valid entry. Please try again: ");
guess = input.nextInt();
}
else
if (guess > answer)
{
System.out.println("Too high, Try Again: ");
guess = input.nextInt();
}
else
if (guess < answer)
{
System.out.println("Too low, Try Again: ");
guess = input.nextInt();
}
input.nextLine();
}
while (guess != answer);
System.out.println("Congratulations, You guessed the number!");
}
我正在使用Java的扫描仪读取用户输入。如果我只使用nextLine一次,它可以正常工作。对于两个nextLine,第一个不等待用户输入字符串(第二个)。 输出: X:Y:(等待输入) 我的代码 你知道为什么会发生这种事吗?谢谢
问题内容: 我正在尝试为我的程序创建一个简单的菜单来读取用户输入。这是代码: 这是我得到的例外测试: 我从while循环中删除了第二个命令= Scanner.next(),但是让我仅读取一次用户输入。怎么解决呢? 更新:AddWord方法: 问题答案: 您可以使用
问题内容: 我正在尝试找出如何创建输入验证的方法,在该方法中,您不能两次输入相同的数字,而且不能在数字范围内输入,除非它是整数,否则无法输入任何内容。我目前正在创建彩票程序,不确定如何执行此操作。任何帮助将非常感激。我的数字范围验证有效,而其他两个验证无效。我尝试了非重复号码验证,但我不确定如何执行仅数字验证。有人可以告诉我如何构建此结构。 此方法在我的Player类中 问题答案: 如下进行: 运
我正在使用useState处理一个待办事项,我试图保存用户输入,然后在他们点击提交后将其推送到listArray,稍后显示它...我认为我在updateArray函数中做错了什么,但我似乎可以理解什么。
当用户输入字符串(例如“”)时,程序应该给出输出“”,然后提示用户键入有效输入。当我键入字符串时,我会在线程“main”java.util.InputMismatchException中得到错误消息