带有trys选项的java游戏



我正在使用Java制作一个猜测游戏,我需要添加一个选项来计算猜测次数,但如果玩家多次给出相同的答案,则会将其计算为1次尝试。

我不知道该怎么办。任何帮助都将不胜感激:(

这是我当前的脚本:

import java.util.Scanner;
public class GuessTheNumber {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() *9);
int guess = 0;
System.out.printf("Guess the number from 1 - 10: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.printf("Lower!: ");
} else if (guess < a) {
System.out.printf("Higher!: ");
}
}
System.out.println("Congratulations! You guessed the number with "
+ count + " tries.");
}
}

您需要使用列表跟踪所有用户的答案,这样,如果在递增之前存在类似的答案,您就可以迭代到列表。

这是朋友

public class GuessTheNumber {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> answers = new ArrayList<Integer>();
;
int count = 0;
int a = 1 + (int) (Math.random() * 9);
int guess = 0;
System.out.printf("Guess the number from 1 - 10: ");
while (guess != a) {
guess = keyboard.nextInt();
boolean isAnswered = false;
for (Integer answer : answers) {
if (guess == answer) {
isAnswered = true;
break;
}
}
if (!isAnswered) {
count++;
answers.add(guess);
}
if (guess > a) {
System.out.printf("Lower!: ");
} else if (guess < a) {
System.out.printf("Higher!: ");
}

}
System.out.println("Congratulations! You guessed the number with "
+ count + " tries.");
}
}

最新更新