turf
turf

Reputation: 183

How to find the largest value from an array in Java?

I am writing a program which can tracking three dices' total appears.Here are my codes:

import java.util.*;

class dice{
    public static void main (String[] args){
        Random rnd = new Random();
        int[] track = new int[19];

        for (int roll=0; roll<10000; roll++){
            int sum=0;
            for(int i = 0; i < 3; i++) {
                //roll the 6-face dice
                int n = rnd.nextInt(6) + 1;
                sum+=n;
            }
            ++track[sum];
        }

        System.out.println("Sum\tFrequency");

        for(int finalSum=3; finalSum<track.length;finalSum++){
            System.out.println(finalSum+"\t"+track[finalSum]);
        }
        System.out.println("the largest frequency is %d", //how to find it?)
    }
}

Now I am almost done. But how can I find the largest appearance and print it separately? Thank you.

Upvotes: 0

Views: 419

Answers (2)

Brunaldo
Brunaldo

Reputation: 66

public int largest(int[] myArr) {
    int largest = myArr[0];
    for(int num : myArr) {
        if(largest < num) {
            largest = num;
        }
    }
    return largest;
}

Set the variable largest to the first item in the array. Loop over the array, whenever the current num you're in is bigger than the current largest value, set largest to num.

Upvotes: 1

Vishrut Majmudar
Vishrut Majmudar

Reputation: 56

You can try below code:

Arrays.sort(arr);
System.out.println("Min value "+arr[0]);
System.out.println("Max value "+arr[arr.length-1]);

Upvotes: 1

Related Questions