java - 每个循环将数字添加到数组

标签 java arrays random

我最近制作了一个快速程序,让计算机猜测您输入的数字。我只是用它来向 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/

相关文章:

使用 jxl.write.WritableImage 图像文件位于 jar 内时出现 java.io.FileNotFoundException

java - 在 RXjava 中应用重试

python 锯齿数组运算效率

c# - 在 C# 中使用线程用随机数填充数组

java - java中按正则表达式模式计数和分割

java - 如果对象引用是静态的,是否意味着该对象的属性也是静态的?

php - 将字符串转换为嵌套数组

arrays - 在 ActionScript 数组 (Object[]) 和 Vector.<Object> 之间转换

c++ - 用 std::uniform_real_distribution<double> 初始化一个 N 大小的 std::vector

python - 在 Python 中生成随机的 6 位数字 ID