【发布时间】:2018-07-08 20:20:30
【问题描述】:
我刚刚开始第一次学习编程,我正在通过 Java 开始学习。我正在做一个使用循环和条件来编写猜谜游戏的常见编码练习。我的程序需要执行以下操作:
- 在 1 到 100 之间选择一个随机数
- 反复提示用户猜数字
- 向用户报告他或她是正确的或猜测很高 或每次猜测后低
- 为用户提供中途退出的选项
- 计算游戏中的猜测次数,并在正确猜测时报告数字
- 询问用户是否想在游戏成功后再次玩游戏
到目前为止,我对循环语法有点不放心,我的程序需要一些帮助,因为有很多问题我不知道如何解决。有人愿意帮我一把吗?请原谅许多可能明显的错误。
导入 java.util.Scanner;
导入 java.util.Random;
公开课猜
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess = 0, count = 0;
String another = "y";
Random generator = new Random();
answer = generator.nextInt(MAX) + 1;
Scanner scan = new Scanner(System.in);
System.out.println("I'm thinking of a number between 1 and " + MAX
+ ". Guess what it is: ");
guess = scan.nextInt();
while (another.equalsIgnoreCase("y"))
{
while (guess != answer)
{
while (guess > MAX || guess < 1)
{
System.out.println("Invalid input. Please re-enter a number"
+ " between 1 and " + MAX + ":");
guess = scan.nextInt();
}
if (guess == answer)
{
count++;
System.out.println("You guessed correctly!");
}
else if (guess > answer)
{
count++;
System.out.println("You guessed too high. Guess again? Y/N:");
another = scan.nextLine();
}
else if (guess < answer)
{
count++;
System.out.println("You guessed too low. Guess again? Y/N:");
another = scan.nextLine();
}
}
}
System.out.println("It took you " + count + "guess(es) to win.");
System.out.println("Do you wish to play again? Y/N:?");
another = scan.nextLine();
count = 0;
answer = generator.nextInt(MAX) + 1;
}
}
【问题讨论】:
标签: java