user10497264
user10497264

Reputation:

How to iterate through array and find highest value: Java

In the Bellow code I am supposed to find the month that correlates with the largest number.

Bellow is what I tried. However I belive that there is likly a more consice way to write this. How can I make it that way?

public class HelloWorld{

static int[] array = {3,6,7,3,2,30,9,13,12,1,2,1};
static String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

static int greatestVal = 0;
static int greatestVal2 = 0;
static String monthChosen = "";

int integer = 0;
static int num = 0;

     public static void main(String []args){
            int number = -1;
            for (int i = 0; i<=11; i++) {
                int currentValue = array[i];
                number += 1;
                //System.out.println(currentValue);
                for (int index = 0; index <=11; index++) {
                    if (currentValue > array[index]) {
                        greatestVal = currentValue;
                        // System.out.println(currentValue +">"+ array[index]);
                        if (greatestVal > greatestVal2) {
                            greatestVal2 = greatestVal;
                            monthChosen = month[number];
                        }
                    } else {
                        // System.out.print("Hgfhdssdgfadkhfdshkjhads");
                    }
                }
        }
            System.out.println(greatestVal2 + " greatest month is: " + monthChosen);
    }
}

Upvotes: 2

Views: 4021

Answers (6)

Benoit
Benoit

Reputation: 5394

With streams:

static int[] array = {3,6,7,3,2,30,9,13,12,1,2,1};
static String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

public static void main(String[] args) {
    int index = IntStream.range(0, array.length)
            .reduce(0, (a, b) -> array[a] >= array[b] ? a : b);
    System.out.println(array[index] + " greatest month is: " + month[index]);
}

Upvotes: 1

Deepali Sinha
Deepali Sinha

Reputation: 44

In Java we have enums where you can have your Constants and the values associated with it. Refer https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Using the approach you may define an enum where name would be month and values can be associated with them.

Now in any other method you can go ahead iterate over the enum values and then find the maximum value. So assume Months is the name of the enum then you can use a simple for-each loop for this:

for (Months months:Months.values()){
  //logic for comparison.find the maximum
}

Note: ENUMS are generally used for constants.So not sure if the described problem is always going to have constant values for each month or it can vary.If it varies then you can go with streams or Maps as described in already given answers.

Upvotes: -1

Alex Savitsky
Alex Savitsky

Reputation: 2371

You don't actually need to keep track of the chosen month for every iteration. Assuming months are related to the array elements by the index, all you need is to find out the index of the greatest element - you don't even need to track the greatest value:

public class HelloWorld {
    static int[] array = {3, 6, 7, 3, 2, 30, 9, 13, 12, 1, 2, 1};
    static String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

    public static void main(String[] args) {
        int index = 0;
        for (int i = 1; i < array.length; i++)
            if (array[index] < array[i])
                index = i;
        System.out.println(array[index] + " greatest month is: " + month[index]);
    }
}

Upvotes: 1

Amit Kumar Lal
Amit Kumar Lal

Reputation: 5789

   public static void main(String []args){
        Integer[] array = {3,6,7,3,2,30,9,13,12,1,2,1};
        String[] month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

        Integer[] copyArr = array.clone();
        Arrays.sort(copyArr);
        int largestNum = copyArr[copyArr.length-1];
        int index = Arrays.binarySearch(array, largestNum);
        System.out.println(month[index]);
     }

output -> June

Upvotes: 0

elvaston5
elvaston5

Reputation: 33

Simplified solution just using your 2 arrays...

    int max = Arrays.stream(array).max().getAsInt();
    int index = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] == max) {
            index = i;
        }
    }
    System.out.println(array[index] + " greatest month is: " + month[index]);

Upvotes: 0

Nicholas K
Nicholas K

Reputation: 15423

if you can use a Map then its very straight forward. Create a HashMap<String, Integer> where the key is the month and value is the count.

You can then iterate over this map and find the key, value pair for which the value is the largest.

Solution :

    Map<String, Integer> monthMap = new HashMap<>();
    // initializing the map
    for (int i = 0; i < 12; i++)
        monthMap.put(month[i], array[i]);

    // finding <k, v> pair with highest entry
    Entry<String, Integer> entry = monthMap.entrySet().stream()
             .max(Map.Entry.comparingByValue(Comparator.comparingInt(i -> i.intValue())))
             .get();

Upvotes: 0

Related Questions