-1

I have managed to print 200 random numbers, from those numbers I want the program to return the largest number out of it.

import java.util.Random;

class random {

    public static int genRandom() {
        return new Random().nextInt(1000000);
    }

    public static void main(String[] args) {
        Random ran = new Random();

        for (int i = 0; i < 200; i++) {
            System.out.println(ran.nextInt(1000000));
        }
    }

}
aboger
  • 2,214
  • 6
  • 33
  • 47
Beno29
  • 11
  • 4
  • 4
    I don't see any attempt here to compare the generated numbers. What code did you write for that ? Tip : the math operator `>` can do wonders to compare numbers – Olivier Croisier May 09 '15 at 19:08
  • possible duplicate of [Generating random integers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) – Jose Ricardo Bustos M. May 09 '15 at 19:23

2 Answers2

1

Not the best answer but according to your code you can use :

static int maxNumber = 0;

public static int genRandom() {
    return new Random().nextInt(1000000);
}

public static void main(String[] args) {
    for (int i = 0; i < 200; i++) {
        int randomNumber = genRandom();
        if (randomNumber > maxNumber) {
            maxNumber = randomNumber;
        }
        System.out.println(randomNumber);
    }
    System.out.println("The largest number is: " + maxNumber);
}
DoubleMa
  • 368
  • 1
  • 8
1

Java Code

public class TestProgram {

    public static void main(String[] args) throws FileNotFoundException {

        Random ran = new Random();

        ArrayList<Integer> randNum = new ArrayList<Integer>();

        for (int i = 0; i < 200; i++) {
            //System.out.println(ran.nextInt(1000000));
            randNum.add(ran.nextInt(1000000));
        }
        //System.out.print(randNum);
        Collections.sort(randNum);
        System.out.println(randNum);
        System.out.println("Largest Number is " + randNum.get(randNum.size()-1));
    }

}
Ritesh Karwa
  • 2,196
  • 1
  • 13
  • 17