我是 Java 新手,所以如果有任何不清楚(或者代码真的很糟糕),请提前道歉,但我正在尝试构建一个程序,让计算机猜测用户输入的两位数代码(即secretCode
)。以下代码工作正常,它将生成一个随机代码,然后与密码进行比较,并检查是否在正确的位置输入了位置。
但是,我将如何做到这一点,以便每次计算机猜测时,它都无法猜测它先前猜测过的数字(例如,如果它在第一次猜测时猜测了 57,则在持续时间内它无法再次选择 57)循环)。基本上我希望计算机跟踪它所做的猜测,而不是再做一次。任何想法这是如何可能的(如果可能,无需大量重写程序)?还是我在这件事上走错了路?
while (guesses < 10)
int[] compCode = computer.getComputerCode(); //This line gets a random two digit array of ints
System.out.print("Computer guess: ");
Arrays.stream(compCode).forEach(System.out::print);
correctPositions = getPosition(compCode, secretCode);
System.out.println("\nYou picked " + correctPositions + " numbers in the correct position.");
guesses++;
}
一种方法是ArrayList
用数字填充 an ,然后将 shuffle ArrayList
:
ArrayList<Integer> guesses = new ArrayList<>();
for(int i =0; i < 100; i++) {
guesses.add(i);
}
//guesses now contains numbers 0-99
Collections.shuffle(guesses);
然后每当你需要一个随机数时,你可以简单地调用一个索引guesses
(确保你跟踪你所在的索引)
一个例子可能是这样的:
while(some_condition) {
//start count at -1, so when we add one it will be 0
//which is the first index of the ArrayList
int count = -1;
//Some code
guesses.get(count++);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句