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
findLargestmethod 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
You should probably create some sort of
initmethod 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.