3 回答
TA贡献1868条经验 获得超4个赞
使用 ArrayList 创建一个数组并为其命名(例如“entered_numbers”)
ArrayList<Integer> entered_numbers = new ArrayList<Integer>();
2. 每次用户输入一个数字时,使用检查contains()该数字是否在ArrayList 中。
如果是,请显示您的消息(不要number_of_guesses++)
如果不是,请使用添加它add()并继续您自己的检查。
if(entered_numbers.contains(user_guess)) {
System.out.println("You have already entered this number");
continue;
} else {
entered_numbers.add(user_guess);
// Check if == secret number,
// Check if < secret number,
// Check if > secret number
}
其他人建议使用HashSets哪个对性能更好。
使用 ArrayList 的复杂度是 O(n),而 HashSet 是 O(1)。
我选择了一种使用 ArrayList 的更简单的方法,它不会对性能产生太大影响,因为您不会在 ArrayList 中存储大量数据。
在此处查看有关复杂性的更多信息:https ://www.baeldung.com/java-collections-complexity
TA贡献1817条经验 获得超6个赞
您可以使用一组来跟踪用户提交的数字,例如
public class GuessingGame2 {
static Scanner kboard = new Scanner(System.in);
public static void main(String args[]) // start of main
{
System.out.println("Welcome to the guessing game, the computer will generate a random number that you have to guess, good luck!");
int secret_number = 0;
int number_of_guesses = 0;
Scanner input = new Scanner(System.in);
int user_guess;
int used_number = 0;
HashSet<Integer> user_inputs = new HashSet<>();
secret_number = (int) (Math.random() * 100) + 1;
System.out.println("The computer has generated it's number");
for (int i = 0; i < 20; i++) {
System.out.println("Please make your guess");
user_guess = kboard.nextInt();
if (!user_inputs.add(user_guess)) {
System.out.println("Please provide another input");
continue;
}
number_of_guesses++;
if (user_guess == secret_number) {
System.out.println("Your guess is correct it took you " +
number_of_guesses + " guesses");
} else if (user_guess < secret_number) {
System.out.println("Your guess is too low try again");
} else if (user_guess > secret_number) {
System.out.println("Your guess is too high try again");
}
System.out.println(20 - number_of_guesses + " Guesses remaining");
}
}
}
添加回答
举报