简体   繁体   中英

Returning the largest number from random numbers

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));
        }
    }

}

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);
}

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));
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM