gpt4 book ai didi

java - 关于java日期比较的困惑

转载 作者:行者123 更新时间:2023-11-29 07:50:29 24 4
gpt4 key购买 nike

预注:

  1. 是的,这是家庭作业。
  2. 我们学校的导师今天不在
  3. 我的书没用
  4. 我不确定在 google 上搜索什么来帮助我解决困惑...

问题:

无论如何 - 我遇到的问题/困惑涉及我程序中用于测试 compareTo 方法的第一段代码。

  1. 我会使用代码顶部的变量作为我在 static void main 区域中的变量,还是像我一样分配新变量?

    <
  2. public Date() 中的值... <-- 这是我在 static void main 中的代码所比较的日期吗? (如果是这样,我有一段我想使用的代码,它使用当前日期,而不是 Date() 中的日期)。

我以后可能会有更多问题,但我希望有人能比我的书或谷歌迄今为止所证明的更好地消除我的困惑。

代码:

package date;
import java.util.*;

public class Date implements Comparable
{
static Scanner console = new Scanner(System.in);

private int dMonth; //Part a of confusion 1
private int dDay;
private int dYear;

public Date()
{
dMonth = 1; //Confusion 2
dDay = 1;
dYear = 1900;
}
public Date(int month, int day, int year)
{
dMonth = month;
dDay = day;
dYear = year;
}
public void setDate(int month, int day, int year)
{
dMonth = month;
dDay = day;
dYear = year;
}
public int getMonth()
{
return dMonth;
}
public int getDay()
{
return dDay;
}
public int getYear()
{
return dYear;
}
public String toString()
{
return (dMonth + "." + dDay + "." + dYear);
}
public boolean equals(Object otherDate)
{
Date temp = (Date) otherDate;

return (dYear == temp.dYear
&& dMonth == temp.dMonth
&& dDay == temp.dDay);
}
public int compareTo(Object otherDate)
{
Date temp = (Date) otherDate;

int yrDiff = dYear - temp.dYear;
if (yrDiff !=0)
return yrDiff;

int monthDiff = dMonth - temp.dMonth;
if (monthDiff !=0)
return monthDiff;

return dDay - temp.dDay;
}

public static void main(String[] args) //Part b of confusion 1
{
int month;
int day;
int year;

Date temp;

System.out.print("Enter date in the form of month day year");
month = console.nextInt();
day = console.nextInt();
year = console.nextInt();
System.out.println();

}
}

最佳答案

如评论中所述,我认为您需要了解静态方法/属性与实例中的方法/属性之间的区别。我认为这是你应该在 main 方法中做的:

System.out.print("Enter date in the form of month day year");
Date date1 = new Date(console.nextInt(), console.nextInt(), console.nextInt());

System.out.print("Enter second date in the form of month day year");
Date date2 = new Date(console.nextInt(), console.nextInt(), console.nextInt());

System.out.println("Comparison result:");
System.out.println(date1.compareTo(date2));

关于你的困惑点:

类属性

 private int dMonth;  //Part a of confusion 1
private int dDay;
private int dYear;

这些是特殊变量。每个实例(即使用 new Date 创建的每个对象)都有自己的 dMonthdDaydYear 值>。它不能从 main 访问,因为 main 是一个静态方法,因此无法访问实例变量。

如果你不明白,至少你知道要进一步搜索的名称。

默认构造函数

public Date()
{
dMonth = 1; //Confusion 2
dDay = 1;
dYear = 1900;
}

当您创建一个新的 Date 对象而没有指定您想要的月/日/年时,将使用这些值。所以 new Date(2, 3, 2013) 表示 2/3/2013,而 new Date() 表示 1/1/1900。

关于java - 关于java日期比较的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com