1

I am trying to print an output that would find the max number and also print the index number of the array as well. I am able to print the max number but I am unable to print the index number.

public static int findMax(int[] allNumbers) {
    int maxValue = allNumbers[0];
    for (int i = 1; i < allNumbers.length; i++) {
        if (allNumbers[i] > maxValue) {
            maxValue = allNumbers[i];
        }
    }
    return (int) maxValue;
}

my array:

int[] allNumbers = new int[inpNum];

I can call the max number with the following findMax(number)

1
  • You don't need to cast maxValue to an int in your return statement. Don't be afraid, it's always an int ;-) Commented Jul 30, 2018 at 16:22

1 Answer 1

2

You can return an array of the max value and index:

public static int[] findMax(int[] allNumbers) {
        int maxValue = allNumbers[0];
        int index = 0;
        for (int i = 1; i < allNumbers.length; i++) {
            if (allNumbers[i] > maxValue) {
                maxValue = allNumbers[i];
                index = i;
            }
        }
        return new int[] {maxValue , index};
}
Sign up to request clarification or add additional context in comments.

5 Comments

when I try this code i am receiving I@55f96302 when my output is printed
@SPJava use the Arrays.toString method. System.out.println(Arrays.toString(findMax(yourArray)));
Thank you! that worked now my only question is if I want to add wording so instead of the output showing: 100, 1 I would want it to be 100 on position 1. Anyway of doing this?
@SPJava store a reference to the returned array and then index into the array to get the corresponding elements, providing your wording... --> int[] result = findMax(yourArray); System.out.println(result[0] + " on position " + result[1]);
question what happens if two numbers are the same how can I print the index number twice? example input numbers 100, 100, 10 should print 100 on position 1 and 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.