【问题标题】:How to return the largest integer in an Array that has 10 random integers in it?如何返回包含 10 个随机整数的数组中的最大整数?
【发布时间】:2019-03-26 03:04:03
【问题描述】:

所以这是我在学校的一个编码问题,我不想说“嘿,伙计们为我做作业!”,我实际上想了解这里发生了什么。我们刚开始研究数组,它们让我感到困惑,所以我正在寻求帮助。 这是完整的问题:

编写一个程序,其中 main 方法创建一个数组 10 个 int 类型的插槽。为每个插槽分配一个随机生成的 整数。调用一个函数,将数组传递给它。被叫 函数应该返回数组中的最大整数到 你的主要方法。您的主要方法应显示数字 回来。使用 Random 对象生成整数。创造它 与

Random r = new Random(7);

生成一个随机整数

x = r.nextInt();

所以,这是我目前所拥有的:

import java.util.Random;
public class Q1 {

    public static void main(String[] args) { 
    Random r = new Random(7);
    int[] count = new int[11];
    int x = r.nextInt();
    for (int i = 0; i < count.length; i++)
    {
        count[i] = x;
    }
}

我用 10 个ints 创建了该数组,然后使用for 循环为每个插槽分配随机生成的整数。

不过,我很难确定下一步该做什么。我不确定要创建什么样的方法/函数,然后如何从那里获得最大的int 并返回它。

非常感谢任何帮助,因为我真的很想了解这里发生了什么。谢谢!

【问题讨论】:

  • 你快完成了。在您的代码 findMax 中添加一个带有参数 int 数组的新方法。迭代循环并在数组中找到大数并将其返回。在 main 方法中调用 findmax 并打印结果。并且 int x = r.nextInt();必须在 for 循环内
  • 想法是每个数组元素都是一个新的随机整数,并不完全相同。
  • 您没有创建一个包含十个随机整数的数组。您创建了一个数组,其中一个随机整数重复了 11 次。去掉变量x 并将for 循环的主体更改为count[i] = r.nextInt();。你的下一步是编写请求的函数,它可能应该有一个类似static int findMax(int[] array) { ... } 的签名。
  • 我已经添加了关于如何制作 int 方法和计算 max number.from 数组的答案。使用代码并询问是否有任何不清楚的地方。一切顺利:)

标签: java arrays random


【解决方案1】:

这里是如何生成随机整数

public static void main(String[] args) {
     int []count = new int[10];
          Random r = new Random(7); 
          int x=0;
        for (int i = 0; i < count.length; i++)
        {
            x = r.nextInt();
            count[i] = x;

        }
       System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number

这里是如何制作方法并从列表中获取最大数量。

static int maxNumber(int[] mArray){//Passing int array as parameter
        int max=mArray[0];
        for(int i=0;i<mArray.length;i++){
            if(max<mArray[i]){//Calculating max Number
                max=mArray[i];
            }
        }

        return max;//Return Max Number.
    }

如果有什么不清楚的地方,请询问。 这就是我们如何制作返回 int 的方法。

【讨论】:

  • 他希望/需要使用随机对象生成随机数。而且我不确定是否有人已经知道如何使用数组。
  • OP的练习需要使用Random r = new Random(7);
  • @joelfischerr 和 LuCio,感谢您指出。我已经更新了我的代码。
【解决方案2】:

您可以通过对数组使用简单的 for 循环来实现。 首先,您必须创建一个单独的 int 变量(例如:int a)并赋值为零 (0),并且在循环的每次迭代中,您必须将数组项与变量 a 进行比较。就这样

a < count[i]

如果是真的,您必须将 count[i] 值分配给变量 a 。这个循环将一直持续到数组的最后一个索引,并且您将在 a 变量中拥有最大的数字。所以只需 SYSOUT 一个变量

重要提示:我没有在此处发布代码,因为我希望您理解这个概念,因为如果您理解它,那么您将来可以自己解决任何这些问题。
希望这会有所帮助

【讨论】:

    【解决方案3】:

    到目前为止,您所得到的几乎是正确的,但您目前在 for 循环的每次迭代中都使用相同的随机数。即使您需要为 for 循环的每次迭代获取一个新的随机数。这是由于 Random 对象是如何定义的。您可以通过以下方式更改代码来实现此目的:

    import java.util.Random;
    public class Q1 {
    
        public static void main(String[] args) { 
        Random r = new Random(7);
        int[] count = new int[11];
        for (int i = 0; i < count.length; i++)
        {
            int x = r.nextInt(); // You need to generate a new random variable each time
            count[i] = x;
        }
    }
    

    请注意,此代码不是最优的,但它是您已有代码的最小更改。

    要从数组中获取最大值,您需要编写另一个 for 循环,然后将数组中的每个值与目前为止的最大值进行比较。您可以通过以下方式执行此操作:

    int largest = 0; // Assuming all values in the array are positive.
    for (int i = 0; i < count.length; i++)
            {
                if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
                   largest = count[i]; // The current value is larger than any value we have seen so far, 
                                      // we therefore set our largest variable to the largest value in the array (that we currently know of)
                   }
            }
    

    当然这也不是最优的,这两件事都可以在同一个 for 循环中完成。但这应该更容易理解。

    【讨论】:

    • > “这可以在一个 for 循环中完成,请在下面查看我的答案” 这就是我在最后两句话中写的字面意思。
    【解决方案4】:

    您的代码应该是这样的。阅读 cmets 以了解它

    public class Assignment {
    
    
    
        public static int findMax(int[] arr) {       // Defiine a function to find the largest integer in the array
            int max = arr[0];          // Assume first element is the largest element in the array
            for (int counter = 1; counter < arr.length; counter++)  // Iterate through the array 
            {
                 if (arr[counter] > max)  // if element is larger than my previous found max
                 {
                  max = arr[counter]; // then save the element as max
                 }
            }
            return max;  // return the maximum value at the end of the array
        }
    
    
    
    
        public static void main(String[] args) { 
    
        int numberofslots =10;
    
        int[] myIntArray = new int[numberofslots];  // creates an array with 10 slots of type int
    
        Random r = new Random(7);
    
        for (int i = 0; i < myIntArray.length; i++)  // Iterate through the array 10 times
        {
    
         int x = r.nextInt();
         myIntArray[i] = x;  // Generate random number and add it as the i th element of the array.
        }
    
        int result =  findMax(myIntArray); // calling the function for finding the largest value 
        System.out.println(result); // display the largest value
    
        }
    }
    

    希望你能通过阅读 cmets 理解代码..

    【讨论】:

    • 随机 r = new Random(7);应该在 for 循环之外 - 以相同的速度创建随机并每次调用 next 一次将生成相同的“随机”数字。所以我们会有相同编号的数组文件
    【解决方案5】:

    这可以在一个简单的 for 循环中完成,不需要有 2 个循环

    public static void main(String[] args) {
            Integer[] randomArray = new Integer[10];
            randomArray[0] = (int)(Math.random()*100);
            int largestNum = randomArray[0];
            for(int i=1; i<10 ;i++){
                randomArray[i] = (int)(Math.random()*100);
                if(randomArray[i]>largestNum){
                    largestNum = randomArray[i];
                }
            }
            System.out.println(Arrays.asList(randomArray));
            System.out.println("Largest Number :: "+largestNum);
        }
    

    【讨论】:

    • 提示:或者只是 Arrays.toString(randomArray) 而不是 Arrays.asList(randomArray)
    • 并注意OP的练习需要使用Random r = new Random(7);
    • 这是不正确的,因为需要使用 Random 类。
    【解决方案6】:

    将最大值初始化为数组的第一个值。然后使用 for 循环迭代数组并检查数组当前值和最大值。 或者您可以sort 数组并返回。祝你好运!

    【讨论】:

    • 你永远不会仅仅为了得到它的最大值而对数组进行排序。这太慢了。
    • 与在 O(n) 中遍历数组一次相比,排序的最小渐近运行时间为 O(n * log(n))。因此,在这种情况下,排序是一个更糟糕的选择。如果您需要 n/2 个最大值,那可能会更好。
    • @joelfischerr 即使对于第 n/2 个元素,也有比排序更好的选择(例如,参见 quickselect)。
    【解决方案7】:

    这是一种基本方法,可以完成您希望完成的相同任务。将其排除在主要方法之外,因此仍然存在一些挑战:)

    public int largestValue(){
      int largestNum;
      int[] nums = new int[10];
      for (int n = 0; n < nums.length; n++){
        int x = (int) (Math.random() * 7);
        nums[n] = x;
        largestNum = nums[0];
        if (largestNum < nums[n]){
          largestNum = nums[n];
        }
      }
      return largestNum;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 2017-04-16
      • 2023-04-11
      • 2021-04-21
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多