0

I also want to compare the max number but I am having problems with inserting it in an array - it gives the error:

java.lang.ArrayIndexOutOfBoundsException 

Whenever I insert a value larger than 5.

import java.util.Scanner;
public class LargestValue 
{
    public static void main(String[] args) 
    {
        Scanner sc= new Scanner (System.in);
        int a[] = new int[5];

        System.out.println ("Enter 5 numbers for comparison ");

        for (int j = 0; j < a.length; j++)
        {
            int inputNumber = sc.nextInt();
            a[inputNumber] = inputNumber;
            System.out.println(inputNumber);
        }
    }
}
1
  • 2
    You meant to use a[j] = inputNumber; instead of a[inputNumber] = inputNumber; Commented Jul 27, 2015 at 8:59

2 Answers 2

2

You should assign the inputs to the j'th position of the array, not to the inputNumber position :

a[j] = inputNumber;
Sign up to request clarification or add additional context in comments.

Comments

0

First error is already postet a[j] = inputNumber;

To compare the array you can use Arrays.sort(a);

Arrays.sort(int): Sorts the specified array into ascending numerical order.

To get the max value you can use Arrays.stream(a).max().getAsInt();

Comments

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.