我有一个简单的任务。有两个类:票证和日期。故障单包含事件,事件地点和事件日期,它是Date对象。我还需要为Date对象提供move()方法,所以我使用了Calendar和Calendar的add()。除了输出之外,一切看起来都很好。我经常为所有Event对象获取相同的日期。 代码:
门票类:
public class Ticket {
private String what;
private String where;
private Date when;
public Ticket(String s1, String s2, Data d){
this.what = s1;
this.where = s2;
this.when = d;
}
public Date giveDate(){
System.out.println("when in giveDate() "+this.when);
return this.when;
}
public String toString(){
return "what: "+this.what+"\n"+"where: "+this.where+"\n"+"when: "+this.when;
}
}
日期类:
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Date {
public int day;
public int month;
public int year;
public Date(int x, int y, int z){
this.day = x;
this.month = y;
this.year = z;
}
public Date move(int p){
Calendar gc = new GregorianCalendar(this.year, this.month, this.day);
gc.add(Calendar.DAY_OF_YEAR, p);
this.year = gc.get(Calendar.YEAR);
this.day = gc.get(Calendar.DAY_OF_MONTH);
this.month = gc.get(Calendar.MONTH);
return this;
}
@Override
public String toString(){
return this.day+","+this.month+","+this.year;
}
}
主要用于测试:
Date date1=new Date(30,4,2002);
Ticket event1=new Ticket("Peter Gabriel's gig",
"London",date1
);
System.out.println(event1);
Ticket event2=new Ticket("Diana Kroll's concert",
"Glasgow",date1
);
System.out.println(event2);
Date date2=event2.giveDate();
date2.move(30);
Ticket event3=new Ticket("X's B-day",
"some place",date2
);
System.out.println(event3);
System.out.println(event1);
System.out.println(event2);
System.out.println(event3);
这是我的输出。创建事件后,他们有适当的日期,但最后你的所有人都得到相同的日期dunno为什么:/
what: Peter Gabriel's gig
where: London
when: 30,4,2002
what: Diana Krall's concert
where: Glasgow
when: 6,12,2004
what: X's B-day
where: some place
when: 5,1,2005
what: Peter Gabriel's gig
where: London
when: 5,1,2005
what: Diana Krall's concert
where: Glasgow
when: 5,1,2005
what: X's B-day
where: some place
when: 5,1,2005
答案 0 :(得分:4)
YEAR
的{{1}},DAY_OF_MONTH
等常量是Calendar
内部使用的整数值。它们表示日历中的字段,而不是值。
您可以通过这种方式获得价值:
Calendar
根据您的更新,首先摆脱gc.get(Calendar.YEAR); (or gc.get(gc.YEAR), but better access it statically)
构造函数。它已被弃用:
日期(int year,int month,int date)
的已过时即可。从JDK 1.1版开始,由Calendar.set(年份+ 1900,月份,日期)或GregorianCalendar(年份+ 1900,月份,日期)取代。
答案 1 :(得分:4)
Bozho已经给出了正确答案,说明为什么你会看到这种特殊行为。但是,这是一个更大问题的症状:首先使用java.util.Calendar。我有两个建议:
Date
java.util.Date
的课程
java.util.{Date,Calendar}
- 请改用Joda Time。这是一个更好的API,这使得更难以犯这种错误。日期和时间都很难,不必与垃圾API作斗争。答案 2 :(得分:0)
好的,所以解决方案如下:
在日期
public Date( Date d){
this.day = d.day;
this.month = d.month;
this.year = d.year;
}
并在Ticket中:
public Ticket(String s1, String s2, Data d){
this.what = s1;
this.where = s2;
this.when = new Date(d);
}