【问题标题】:Adding numbers to an array each loop每次循环将数字添加到数组中
【发布时间】:2016-02-10 06:37:56
【问题描述】:

我最近做了一个快速程序,让计算机猜你输入的数字。我只是用它来向朋友展示一个 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.");
}

【问题讨论】:

  • 你不知道怎么办?
  • 考虑集合而不是数组。这种情况(“以前是否遇到过这个值”)非常适合它。
  • 到目前为止你做了哪些努力?
  • 我会创建一个数组并通过 GuessNum 对其进行索引,然后我会使用另一个 while 循环来检查所有结果并查看它们是否已经完成。
  • 对不起,我今天出去了。感谢您的回复,我将尝试看看我能做些什么!

标签: java arrays random


【解决方案1】:

您可能想要使用ArrayList(一个动态增加的数组)

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(num);

如果您想查看该数字是否已添加到数组列表中

if(list.contains(num))
{
 System.out.println("You already tried " + num);
}

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);
}

【讨论】:

  • new HashSet();new ArrayList(); 创建原始类型。你应该avoid 原始类型。使用菱形符号,例如new HashSet&lt;&gt;();
【解决方案2】:

使用HashSet&lt;Integer&gt; 来执行此操作。 Set 中的值是唯一的,因此这是存储已经猜到的值的简单方法。

contains(...) 方法是你如何知道你之前是否猜过这个数字

【讨论】:

    【解决方案3】:

    Java 中的数组是固定大小的。分配数组后,仅允许添加不超过您预先分配的元素数量的元素。在您的情况下这不是一个大问题,因为值限制为 100,但您有更好的选择:

    Java 库提供动态增长的集合。在您的情况下,HashSet&lt;Integer&gt; 将是一个不错的选择:

    • HashSet 可以随意增长到任意大小
    • 检查HashSet 的号码是一种快速操作

    另一种解决方案是创建一个包含 101 个 booleans 的数组:

    boolean[] seen = new boolean[101];
    

    现在您可以通过将seen[myGuess] 测试为false 来检查该号码是否曾被查看过,并在您看到新号码时设置seen[myGuess] = true。这种方法也非常快。但是,您需要跟踪您有多少可用数字,因为从 1 到 100 的范围将在 100 次猜测后耗尽,因此尝试生成额外的数字将成为无限循环。

    【讨论】:

    • ArrayList 大小不固定。
    • @MuratK。 ArrayList 和我的回答有什么关系?
    【解决方案4】:

    Set 是该功能的合适容器。你可以这样定义它:

    Set<Integer> previous = new HashSet<>();
    

    并且得到一个你以前没有尝试过的随机数

    while (previous.contains(MyGuess))
        MyGuess = rand.nextInt(100) + 1;
    previous.add(MyGuess);
    

    这将从rand 对象中获取新的随机数,直到找到不在previous 中的随机数。然后将其添加到previous 以进行下一次迭代。

    【讨论】:

      【解决方案5】:

      最简单的方法是添加一个 ArrayList 并检查列表是否包含随机值:

      Ar first you make and new ArrayList:

      ArrayList<Integer> myGuesses = new ArrayList();
      

      第二步,将随机值添加到列表中:

      ArrayList<Integer> myGuesses = new ArrayList();
      

      现在您只需检查列表是否包含该值,然后再生成一个新值并计算您的尝试次数:

      if(myGuesses.contains(MyGuess))
      {
         //your code
      }
      

      我将此应用于您的代码:

      Scanner scan = new Scanner(System.in); // Number to guess //
              Random rand = new Random(); // Generates the guess //
              int GuessNum = 0, RandGuess = 0;
              ArrayList<Integer> myGuesses = new ArrayList();
      
              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) {
      
                      if(myGuesses.contains(MyGuess))
                      {
                          MyGuess = rand.nextInt(100) + 1;
                          GuessNum++;
                          myGuesses.add(MyGuess);
                      }
                  }
                  System.out.println("I guessed the number after " + GuessNum + " tries.");
              }
      

      希望对你有帮助!

      【讨论】:

        【解决方案6】:

        一个非常简单的例子是:

        public static int[] randomArray(){
            int number = Integer.parseInt(JOptionPane.showInputDialog("How many numbers would you like to save?: "));       //Get Number of numbers from user
            int[] array = new int[number];  //Create the array with number of numbers (by User)
            for(int counter = 0; counter < number; counter++){      //For loop to get a new input and output every time
                int arrayString = (int) (Math.random() * 10);
                array[counter] = arrayString;
                System.out.println("Number " + (counter + 1) + " is: " + array[counter]);   //Print out the number
            }
            return array;
        }
        

        此示例在每次循环重复时添加数字,只需将随机数替换为您想要的数字即可。

        【讨论】:

          猜你喜欢
          • 2020-10-22
          • 1970-01-01
          • 2019-01-07
          • 1970-01-01
          • 2023-03-26
          • 1970-01-01
          • 2013-07-25
          • 2019-04-03
          • 1970-01-01
          相关资源
          最近更新 更多