java.lang.ArrayIndexOutOfBoundsException: 0 - Arra

2020-02-06 07:19发布

问题:

Does the exception thrown indicate that the array is larger than the index? If not, what does it mean, and why? How do I correct it?


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at leapyear.LeapYear.main(LeapYear.java:13)


public class LeapYear {

public static void main(String[] args) { 
    int year = Integer.parseInt(args[0]);
    boolean isLeapYear;

    // divisible by 4
    isLeapYear = (year % 4 == 0);

    // divisible by 4 and not 100
    isLeapYear = isLeapYear && (year % 100 != 0);

    // divisible by 4 and not 100 unless divisible by 400
    isLeapYear = isLeapYear || (year % 400 == 0);

    System.out.println(isLeapYear);
}
}

回答1:

The array doesn't contain any elements--it is an empty array. So when you ask for the first element in the array (the element contained at index 0) the array says "I don't have an element at index 0". It 'says' this by throwing an exception. In your case, the exception is java.lang.ArrayIndexOutOfBoundsException: 0

This means that the index you requested is outside the bounds of the array. In other words, the array has a length (it's bounds). When it's length is 0 (it's empty) and you ask for the 1st element, the array tells you the item you requested is unavailable because the array isn't even 1-element long.



回答2:

It means the array is smaller than the index. In that case it means the array is empty.

You should pass a command-line argument in order to have a value there. And if it is required, you'd better add some validation, like

if (args.length == 0) {
    throw new IllegalArgumentException("year is required");
}


回答3:

It means that it is smaller than the index. In other words, there were no command line arguments, and you are assuming that there was at least one.



回答4:

You're accessing an index of the array which does not exist. This would happen for any index less than 0 or greater or equal to the length of the array.

Add this

if(args != null || args.length < 1) {
  throw new IllegalArgumentException("Please provide an argument.");
}


回答5:

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Here's a check against that.

public static void main(String[] args) { 
if (args.length != 1){
    System.out.println("Year Required")
    System.exit(0);
}
    int year = Integer.parseInt(args[0]);
    boolean isLeapYear;

    // divisible by 4
    isLeapYear = (year % 4 == 0);

    // divisible by 4 and not 100
    isLeapYear = isLeapYear && (year % 100 != 0);

    // divisible by 4 and not 100 unless divisible by 400
    isLeapYear = isLeapYear || (year % 400 == 0);

    System.out.println(isLeapYear);
}