如何在java上保存一个值

时间:2014-01-31 01:04:00

标签: 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));
}

3 个答案:

答案 0 :(得分:0)

如果我正确理解您,您希望添加到添加到创建对象的基础值。现在,你有一个通过执行维持状态的对象,所以当你说dateTime1.addDays(366)时,它会永久地修改那个对象。

您必须提供功能来保留传递给构造函数的值以“重置”,或者在每次修改后重新实例化DateTime对象。

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

答案 1 :(得分: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));
}

答案 2 :(得分:0)

如果在每个system.out之前重新创建对象,您将获得所需的结果。

似乎您的对象正在重复使用

您的代码中缺少“dateTime1”的声明,然后我们假设它是一个类属性,但您应该在您的问题中显示它的声明位置。