[英]How to avoid return null on my case?
我需要编写一个Java程序(Date类)和“ NextDay类,通过输入日,月和年来计算并打印第二天的日期”。
在public Date getNextDay()
方法中,我必须使用return null,否则会出错。 如何避免返回null?
这是我的代码;
public class Date {
private int day;
private int month;
private int year;
public Date(int day, int month, int year){
this.day = day;
this.month = month;
this.year = year;
}
public int getMaxDaysInMonth()
{
int daysInMonth = 0;
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysInMonth = 31;
break;
case 2:
if(isLeapYear())
{
daysInMonth = 29;
}
else
{
daysInMonth = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
daysInMonth = 30;
}
return daysInMonth;
}
public Date getNextDay(){
try {
if(day < getMaxDaysInMonth()){
return new Date(day + 1, month, year);
}
else if(day == getMaxDaysInMonth() & month < 12){
return new Date(1, month+1, year);
}
else if(day == getMaxDaysInMonth() & month == 12){
return new Date(1, 1, year+1);
}
} catch (Exception e) {
System.out.println("You have entered an invalid Date.");
e.printStackTrace();
}
return null;
}
public int getDay(){
return day;
}
public int getMonth(){
return month;
}
public int getYear(){
return year;
}
public boolean isLeapYear(){
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public String toString(){
return this.day + "." + this.month + "." + this.year;
}
}
public class NextDay {
public static void main(String args[]) throws Exception{
Date dateObj = new Date(28, 2, 2015);
System.out.println("Old Date: " + dateObj.getDay() + "." + dateObj.getMonth() + "." + dateObj.getYear() + ".");
System.out.println("The next day is " + dateObj.getNextDay().toString() + ".");
}
}
使用局部变量并将其赋值并在方法末尾返回,如果可以提高性能,则可以在代码中使用跳跃语句
public Date getNextDay(){
Date date = new Date();
try {
if(day < getMaxDaysInMonth()){
date= new Date(day + 1, month, year);
}
else if(day == getMaxDaysInMonth() & month < 12){
date = new Date(1, month+1, year);
}
else if(day == getMaxDaysInMonth() & month == 12){
date = new Date(1, 1, year+1);
}
} catch (Exception e) {
System.out.println("You have entered an invalid Date.");
e.printStackTrace();
}
return date;
}
我建议抛出一个异常。 作为例外的一部分,您还可以给出关于was / is错误的解释。
返回特定日期不是一个好主意,因为该日期也可能与以有效方式创建的日期匹配。 即可以轻松创建Date 01-01-1970,对吗? 因此,不应将其作为问题的种类或标记返回。
关于日期表示形式,请记住,可以使用Integer.MAX_VALUE初始化月份,日期和年份的日期。 在这种情况下,预期输出是多少?
我建议您返回过去的日期,并避免返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.