当我需要将 5 个用户输入的值存储到一个数组中,将其发送到一个方法,并找到并显示最小值时,我一直在研究这个基本的 java 程序。
该程序很简单,并且可以运行,但是当我输入最后一个数字时,出现错误:
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 4 at minNumber.main(minNumber:14)
帮助?
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);
}
}