Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an array with 1000 randomly generated ints?

Tags:

java

arrays

int

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.

like image 577
Bryan Avatar asked Sep 15 '26 04:09

Bryan


2 Answers

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.

like image 156
hvgotcodes Avatar answered Sep 17 '26 19:09

hvgotcodes


int n[] = {1,5,7,3};
    for(int i=0;i<n.length;i++){
        if(n[i] > n[0]){
        n[0] = n[i];
        }
    }
    System.out.println(n[0]);
like image 32
Krishna Kumar Chourasiya Avatar answered Sep 17 '26 19:09

Krishna Kumar Chourasiya