如何创建1000个随机产生的整数数组? [英] How do I create an array with 1000 randomly generated ints?

查看:206
本文介绍了如何创建1000个随机产生的整数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该创造1000整数数组和写入找到最大的INT,然后打印出来的方法。这是我到目前为止有:

 公共静态INT findLargest(INT []号){
    INT最大=号码[0];
    的for(int i = 1; I< numbers.length;我++){
        如果(数字[Ⅰ]≥最大){
            最大数量= [I]
        }
    }
    最大的回报;
}

首先,我该如何创建具有1000随机生成的整数数组?我试图 INT []数组=新(INT)(的Math.random()); ,但我不知道如何得到它做1000的随机数。其次,我怎么打印出结果?感谢您事先的任何帮助。


解决方案

目测它,你的 findLargest 方法看起来不错 - 它是用正确的方法。

要产生1000个号码的列表,你需要在数组初始化为1000元。现在要初始化它有元素的随机数,这是不是你想要的。在初始化号码是int [长度1000],你需要循环数组把一个随机数超过一些类似

  INT []号= INT新[1000]; //生成新的int []对于(i = 0; I< number.length;我++){
  编号[i] = XXXX; //生成一个随机数
}

您也许应该建立某种形式的的init 方法,为您创建原始数组。你会调用它主,拿到引用数组,然后通过该数组的查找方法,然后打印出结果。

您几乎没有。

I am supposed to create an array of 1000 ints and write a method to find the largest int and then print it. This is what I have so far:

public static int findLargest(int[] numbers){  
    int largest = numbers[0];  
    for(int i = 1; i < numbers.length; i++){  
        if(numbers[i] > largest){  
            largest = numbers[i];  
        }  
    }  
    return largest;
}

First, how do I create an array with 1000 randomly generated ints? I tried int[] array = new (int)(Math.random()); but I don't know how to get it to do 1000 random numbers. Second, how do I print the result? Thanks in advance for any help.

解决方案

Eyeballing it, your findLargest method looks good -- it is using the correct approach.

To generate the list of 1000 numbers, you need to initialize the array to 1000 elements. Right now you are initializing it to have a random number of elements, which is not what you want. After you initialize the numbers to be an int[] of length 1000, you need to loop over the array putting a random number in. Some something like

int [] numbers = new int[1000]; // generate a new int[]

for (i = 0; i < number.length; i++) {
  numbers[i] = xxxx; // generate a random number
}

You should probably create some sort of init method that creates the original array for you. You would invoke it in main, get the reference to the array, then pass that array to your find method, then print the result.

You are almost there.

这篇关于如何创建1000个随机产生的整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆