3 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用 ArrayList 創(chuàng)建一個(gè)數(shù)組并為其命名(例如“entered_numbers”)
ArrayList<Integer> entered_numbers = new ArrayList<Integer>();
2. 每次用戶輸入一個(gè)數(shù)字時(shí),使用檢查contains()該數(shù)字是否在ArrayList 中。
如果是,請顯示您的消息(不要number_of_guesses++)
如果不是,請使用添加它add()并繼續(xù)您自己的檢查。
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哪個(gè)對性能更好。
使用 ArrayList 的復(fù)雜度是 O(n),而 HashSet 是 O(1)。
我選擇了一種使用 ArrayList 的更簡單的方法,它不會對性能產(chǎn)生太大影響,因?yàn)槟粫?ArrayList 中存儲大量數(shù)據(jù)。
在此處查看有關(guān)復(fù)雜性的更多信息:https ://www.baeldung.com/java-collections-complexity

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用一組來跟蹤用戶提交的數(shù)字,例如
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");
}
}
}
添加回答
舉報(bào)