我知道这很简单,但我无法弄清楚为什么我一直得到越界异常。我尝试过以不同的方式初始化数组,但仍然无济于事。我在toString方法中得到异常,并在检查日期是否在其定义的月份的正确范围内的部分。
public class MyDate
{
//variables for year day and month.
private int year, day, month;
//variable for n which is used to compare to the days for leap years.
int n;
String[] Months = {"January","Feburary","March","April","May","June","July"
,"August" ,"September","October","November","December"};
int[] MaxDays = {31,31,31,30,31,30,31,31,30,31,30,31};
public MyDate(int year, int day, int month)
{
//Checks to see if the year is valid.
if (year < 1600 || year > 3000)
{
System.out.println("The year entered is not valid, "
+ "You entered: " + year);
System.out.println("The year must be between 1600 and"
+ " 3000.");
System.exit(0);
}
//Checks to see if the month is valid.
if (month < 1 || month > 12)
{
System.out.println("The month is not valid, " + "You Entered: "
+ month);
System.out.println("The month must be between 1 and 12.");
System.exit(0);
}
//Checks to see if the day is valid
if (day >= MaxDays[this.day - 1])
{
advance();
}
//Checks for a leap year, and if the day is valid or not.
if ((year % 400 == 0) || (year % 100 != 0))
{
if (year % 4 == 0)
{
if (month == 2)
{
//Loops that goes from 27-31 comparing the day to n.
int n = 27;
do
{
if (n == day)
{
System.out.println("This is a leap year, and you entered " + n + " as the day"
+ "\n" + "this day is not valid for a leap year");
System.out.println();
break;
}
if (n == 32)
{
break;
}
n++;
}
while (n == day);
}
}
}
else
{
this.year=year;
this.day=day;
this.month=month;
}
}
//Checks to see if two dates are equal to eachother.
public boolean equals(Object obj)
{
if (obj instanceof MyDate){
MyDate d = (MyDate)obj;
if (this.getMonth()==d.getMonth() && this.getDay()==d.getDay() &&
this.getYear()==d.getYear())
return true;
else
return false;
}
return false;
}
//gives a general format for the month day and year.
public String toString()
{
return Months[month - 1] + " " + day + "," + year + "";
}
答案 0 :(得分:1)
似乎问题来自那里
if (day >= MaxDays[this.day - 1])
其中this.day = 0
我想你应该通过month
。
if (day >= MaxDays[month - 1])
<强>更新强>
在toString()
方法month
= 0中,因为您之前没有设置过月份
在构造函数中阻止this.month=month;
阻止else
。
答案 1 :(得分:0)
可能错误就在这里,在if condition
if (day >= MaxDays[this.day - 1])
MaxDays []是一个包含12个元素的数组 - 索引0 - 11
days can be from 1-31,
所以如果day is greater than 12, it will give an IndexOutOfBoundException.
在你的代码中虽然它总是为零,因为你在使用它之前没有初始化它。