2

I am trying to print the largest value from an array set but I keep getting an out of bounds error. I am unsure of how exactly fix it. Here is my code:

Scanner console = new Scanner(System.in); System.out.print("Please enter the name of the input file: "); String inputFileName = console.nextLine(); Scanner in = null; try { in = new Scanner(new File(inputFileName)); } catch (FileNotFoundException e) { System.out.print("Error!"); e.printStackTrace(); } int n = in.nextInt(); double[] array = new double[n]; for (int i = 0; i < array.length; i++) { array[i] = in.nextDouble(); } console.close(); double largest = array[n]; // Exception occurs here for (int i = 0; i < n; i++) { if (array[i] > largest) { largest = array[i]; } } System.out.println("The largest value in the data is: " + largest); 

Any help is greatly appreciated.

2 Answers 2

3

Change

double largest = array[n]; 

to

double largest = array[0]; 

array[n] causes the ArrayIndexOutOfBoundsException, since n is not a valid index of your array.

This will also allow you to change

for (int i = 0; i < n; i++) 

to

for (int i = 1; i < n; i++) 
Sign up to request clarification or add additional context in comments.

2 Comments

That could result in a ArrayIndexOutOfBoundsException too, if the array has zero length. A safe alternative for all array lengths would be double largest = Double.NEGATIVE_INFINITY (or checking that the array is non-zero length, of course).
@AndyTurner or you can add a validation that requires n to be positive, since otherwise this entire code is pointless.
3

Unless You have asked to do it manually , You can also (easily) use the built in function Arrays.sort(array); which sorts the array and then access the largest element(the last one in the array) :

double[] array = new double[n]; Arrays.sort(array); double maxValue = array[array.length-1]; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.