import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
int target;
int guess;
Random randomGenerator = new Random();
Scanner keyboard = new Scanner(System.in);
int game = 0;
int score = 1;
String answer;
do {
target = randomGenerator.nextInt(100);
System.out.print("Guess a number between 1 and 100: ");
guess = keyboard.nextInt();
while (guess != target) {
if (target < guess)
System.out.println("The number is lower, Try again");
else
System.out.println("The number is higher, Try again");
System.out.print("Guess a number between 1 and 100: ");
guess = keyboard.nextInt();
score++;
}
System.out.println("You guessed correctly!!");
System.out.println("Your score is " + score);
System.out.print("Play another game, yes(or no):");
answer = keyboard.next();
game++;
score = 1;
} while (answer.equalsIgnoreCase("yes"));
// end of game information
System.out.println("Game summary");
System.out.print("\tNumber of games played:\t" + game);
System.out.println("\tbest score" + score);
}
}
我正在通过制作一个猜数字游戏来学习如何使用Random类,该猜数字游戏会生成一个介于1到100之间的数字。每当用户进行猜测时,分数就会上升。我不确定如何打印最低分数。该程序将两个游戏的总得分相加,而不是打印最低得分。
答案 0 :(得分:0)
在打印之前,需要先对其进行计算。
需要两件事: 1.每局得分 2.迄今为止的最低分
为了让您的“得分”变量计算当前游戏的得分,需要将每个游戏的得分重置为1。因此,score = 1
在新游戏开始的do {
之后。
为了跟踪最低价,您需要声明int lowestScore = 999999999
(稍后说明),并在每局游戏之后(就在guess != target
的循环之外)编写if (score < lowestScore) lowestScore = score
。 / p>
为什么是999999999?好吧,这是一种确保将第一个分数记住为最低分数的便宜方法,该分数将是迄今为止定义的最低分数。除非您有愿意输入十亿个错误猜测的人。