0

I have been working on this basic java program when I need to store 5 user entered values into an array, send it to a method, and find and display the lowest value.

The program is simple enough, and it runs, but when I enter the last number, I get the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at minNumber.main(minNumber:14)

Help?

import java.util.*;

class minNumber {


    public static void main(String args[]){

    Scanner input = new Scanner(System.in);

    int numberArray[] = new int[4];
    int findLowest;

    for (int i = 0; i <= numberArray.length; i++){
        System.out.println("Enter a value for slot "+(i+1)+ ":");
        numberArray[i] = input.nextInt();   
    }
    findLowest = getMin(numberArray);
    displayOutput(findLowest);
}

public static int getMin(int num[]){

int lowestNum = 0;
for (int j = 0; j <= num.length; j++){
    if (num[j] < num[j+1]){

        lowestNum = num[j];
    }
}
return lowestNum;
}

public static void displayOutput(int lowest){

System.out.println("The lowest number is: "+lowest);
}
}
Kakalokia
  • 3,191
  • 3
  • 24
  • 42
tserran
  • 53
  • 1
  • 4
  • 13

3 Answers3

3

First, if you want 5 values in an array, then declare it with 5:

int numberArray[] = new int[5];

Second, you are going off the end of the array. Change

for (int i = 0; i <= numberArray.length; i++){

to

for (int i = 0; i < numberArray.length; i++){

You'll need to change your other j for loop this way also.

As an aside, your getMin method needs another change besides the change I mentioned above, because saying num[j+1] will still run off the end of the array even if you make the change above. I think you'll need to compare the current array element versus lowestNum, not the next array element.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • In the second for-loop there is also the if-statement which checks `if(num[j] < num[j+1])`. This will also get an ArrayIndexOutOfBounds Exception. Here he has to change the code, too. – Loki Mar 19 '13 at 18:15
  • The error changed to Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at minNumber.getMin(minNumber.java:24) at minNumber.main(minNumber:16) – tserran Mar 19 '13 at 18:15
  • @Loki: Right, I was getting to that. – rgettman Mar 19 '13 at 18:16
0

<= numberArray.length should become < numberArray.length

since arrays are 0 indexed.

smk
  • 5,340
  • 5
  • 27
  • 41
0

Remove the = in both loop.

public static void main(String args[]){
   .......
   for (int i = 0; i < numberArray.length; i++){
       ........
   }
   .........
}

and

public static int getMin(int num[]){
 .....
   for (int j = 0; j < num.length -1 ; j++){

   }
   ....
}
Ajay S
  • 48,003
  • 27
  • 91
  • 111