Tiffany Phu Tiffany Phu - 2 months ago 6
Java Question

How do I find the greatest number in a random set of numbers using an array for Java?

This is what I have so far, but it only compares number with itself. I need it to compare with all 100 numbers. Thank you!

import java.util.Random;

public class CompSci {
public static void main(String[] args) {
Random generator = new Random();

for (int x = 1; x < 100; x++) {
int num1 = generator.nextInt(100);
System.out.println ("A number from 1 to 100: " +num1);

int numbers[] = new int[]{num1};
int largest = numbers[0];

for(int i = 1; i < numbers.length; i++) {
if(numbers[i] > largest)
largest = numbers[i];
}
System.out.println("Largest Number is: " + largest);
}
}
}

Answer

For each iteration of your outer loop you are creating a new array, so move the

int numbers[] array to before the first for loop.

In this case you can set the size of this array to 100 as that will be how many times you will iterate.

Also the value of largest should also be kept outside the loop, and if so then you do not need to loop through all numbers in the array, just the last entered number. In fact you do not even need the number array.

try

import java.util.Random;

public class CompSci {
  public static void main(String[] args) {
    Random generator = new Random();

    int numbers[] = new int[100];     // not even really needed for this exercise
    int largest = Integer.MIN_VALUE;  // a very small number

    for (int x = 1; x < 100; x++) {
        int num1 = generator.nextInt(100);
        System.out.println ("A number from 1 to 100: " +num1);

        numbers [x] = num1;
        if(numbers[x] > largest)
        {
            largest = numbers[x]; //Set if find new largest number
        }
         System.out.println("Largest Number is: " + largest);
    }
}

Note

Also check the javadocs (Thanks @Andreas)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive),