【发布时间】:2013-02-19 00:52:02
【问题描述】:
我要做的是访问一个对象,在本例中为 date1,它有 3 个属性日、月和年。我正在尝试创建一个名为 showTomorrow() 的方法,它将以字符串格式显示对象信息 1 天。这意味着我无法更改原始对象的属性。
我已经编写了 Data.java 程序,它如下所示,如果有人能指出正确的方向或告诉我它真正有用的地方。
我相信这就是我在主要方法上运行的基本方法。
**Date date1 = new Date(30, 12, 2013)** // instantiate a new object with those paramaters
**date1.showDate();** // display the original date
**date1.tomorrow();** // shows what that date would be 1 day infront
问题是现在它没有显示任何内容。我想通过说 dayTomorrow = this.day++;我将它的默认值 + 1 天添加到变量 dayTomorrow。
public class Date
{
private int day;
private int month;
private int year;
private int dayTomorrow;
private int monthTomorrow;
private int yearTomorrow;
public Date()
{
day = 1;
month = 1;
year = 1970;
}
public Date(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public void setDate(int inDay, int inMonth, int inYear)
{
day = inDay;
month = inMonth;
year = inYear;
}
public String getDate()
{
String strDate;
strDate = day + "/" + month + "/" + year;
return strDate;
}
public String getTomorrow()
{
String strTomorrow;
strTomorrow = dayTomorrow + "/" + monthTomorrow + "/" + yearTomorrow;
return strTomorrow;
}
public String tomorrow()
{
dayTomorrow = this.day++;
monthTomorrow = this.month;
yearTomorrow = this.year;
if(dayTomorrow > 30)
{
dayTomorrow = 1;
monthTomorrow = this.month++;
}
if(monthTomorrow > 12)
{
monthTomorrow = 1;
yearTomorrow = this.year++;
}
return getTomorrow();
}
public void showDate()
{
System.out.print("\n\n THIS OBJECT IS STORING ");
System.out.print(getDate());
System.out.print("\n\n");
}
public void showTomorrow()
{
System.out.print("\n\n THE DATE TOMORROW IS ");
System.out.print(getTomorrow());
System.out.print("\n\n");
}
public boolean equals(Date inDate)
{
if(this.day == inDate.day && this.month == inDate.month && this.year == inDate.year)
{
return true;
}
else
{
return false;
}
}
}
【问题讨论】:
-
那么,每年都是闰年吗?不要滚动你自己的代码来操纵日期。
-
你是在 date1.tomorrow() 之后调用 showDate() 吗?
-
我完全同意@JackManey。请找一个图书馆来处理这个问题。强烈推荐Joda Time。原生 Java 时间的东西有点烂:(
-
我需要这样做,因为这是要求我完成的工作。
-
@MarioStanicic - 然后向他们解释为什么这样做是 a) 一个糟糕的想法,b) 构建、测试和使用比使用日期操作库慢得多,以及 c) 将导致错误。
标签: java string oop methods void