2014-01-31 32 views
-4

这是我在java上的第一个月。我每次调用方法时都会收到一个逻辑错误,它会更新此值。如何修复此问题并使其成为静态,以便每次原始数据和时间都不会发生变化。如何在java上保存一个值

结果:

testing 7 arg constructor with initial date: [2-28-2015],[12:30:30:0] 
Increasing day by 366 [2-29-2016],[12:30:30:0] 
Increasing month by 12 [2-28-2017],[12:30:30:0]<---- should be 2016 
Increasing year by 2 [2-28-2019],[12:30:30:0]<-------should be 2017 
Initial date is [2-28-2016],[12:30:30:0] 
Increasing day by 365 [2-27-2017],[12:30:30:0] 
Increasing month by 11 [1-27-2018],[12:30:30:0] 
Increasing year by 30 [1-27-2048],[12:30:30:0] 

这里是我的代码:

public class DateTime implements DateConstants {  
private Date date; // from Date Class 
private Time time; // from Time class 
} 
public DateTime addMonths(int mo) 
{ 
this.date.addMonths(mo); 
return this; 
} 
public static void main(String[] myArgs) { 
dateTime1 = new DateTime(2,28,2015,12,30,30,0); 
System.out.println("testing 7 arg constructor with initial date: "+dateTime1); 
System.out.println("Increasing day by 366 "+dateTime1.addDays(366)); 
System.out.println("Increasing month by 12 "+dateTime1.addMonths(12)); 
System.out.println("Increasing year by 2 "+dateTime1.addYears(2)); 
} 
+1

'静态'在这里使用完全是错误的词。它已经有了明确的含义,这不是它。 – EJP

+0

你的意思是,public static final DateTime addMonths(int mo)? – Rishav

回答

0

如果我正确认识你,你希望你的补充添加到该对象与创建的基本价值。现在,您有一个对象通过执行保持其状态,因此当您说dateTime1.addDays(366)时,它将永久修改该对象。

您必须放入函数来保存传递给构造函数的值以“重置”到每个修改后的DateTime对象或重新实例化对象。

正如其他人所说,static这个词是有意义的,这是不合适的。请改变你的头衔。

+0

是的,你了解我的观点。让我看看那将是什么解决方案。谢谢。 – Rishav

0

如果我正确理解你的问题,我想你可以试试这个

public class DateTime implements DateConstants {  
private Date date; // from Date Class 
private Time time; // from Time class 

} 
public DateTime addMonths(int mo) 
{ 
    DateTime temp=this.clone(); 
    return temp.date.addMonths(mo); 

} 
public static void main(String[] myArgs) { 
dateTime1 = new DateTime(2,28,2015,12,30,30,0); 
System.out.println("testing 7 arg constructor with initial date: "+dateTime1); 
System.out.println("Increasing day by 366 "+dateTime1.addDays(366)); 
System.out.println("Increasing month by 12 "+dateTime1.addMonths(12)); 
System.out.println("Increasing year by 2 "+dateTime1.addYears(2)); 
} 
+0

仍然给出相同的结果。 – Rishav

0

,如果你重新创建的每个System.out的对象之前,你会得到你想要的结果。

看来你的对象被重复使用

“dateTime1”的声明从您的代码丢失,然后我们假设it's类属性,但你应该在你的问题显示在声明。