我最近制作了一个快速程序,让计算机猜测您输入的数字。我只是用它来向 friend 展示一个 While 循环的例子。我决定要让它变得更复杂,但我不确定该怎么做。
我希望将每个随机猜测添加到一个数组中,这样它就不会多次猜测同一个数字。
Scanner scan = new Scanner (System.in); // Number to guess //
Random rand = new Random(); // Generates the guess //
int GuessNum = 0, RandGuess = 0;
System.out.println("Enter a number 1 - 100 for me to guess: ");
int input = scan.nextInt();
if (input >= 1 && input <= 100)
{
int MyGuess = rand.nextInt (100) + 1;
while ( MyGuess != input)
{
MyGuess = rand.nextInt (100) + 1;
GuessNum++;
}
System.out.println ("I guessed the number after " + GuessNum + " tries.");
}
最佳答案
你可能想使用一个ArrayList
(一个动态递增的数组)
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(num);
如果你想看看这个数字是否已经添加到arraylist中
if(list.contains(num))
{
System.out.println("You already tried " + num);
}
A Set
也是相当好的选择。它与 ArrayList
相同,但不允许重复。
HashSet<Integer> set = new HashSet<Integer>();
set.add(num);//returns true if the num was not inserted before else return false
if(!set.add(num))//set also has a contains method
{
System.out.println("You already entered " + num);
}
关于java - 每个循环将数字添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612131/