如何在java上保存值

如何在java上保存值,java,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]<----

这是我学习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]

如果我理解正确,您希望添加的内容添加到创建对象时使用的基本值中。现在,有一个对象通过执行来保持其状态,所以当您说
dateTime1.addDays(366)
,它将永久地修改该对象

您必须输入功能以保留传递到构造函数中要“重置”的值,或者在每次修改后重新实例化
DateTime
对象


正如其他人所说,
static
一词有其含义,这是不恰当的。请更改您的标题。

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

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));
}

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

您的对象似乎正在被重用


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

这里使用的“static”一词完全错误。它已经有了一个很好的定义,但不是这样。你的意思是,公共静态最终日期时间addMonths(intmo)?是的,你明白我的意思了。让我看看解决方案是什么。谢谢。结果还是一样的。
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));
}