【发布时间】:2018-08-20 19:59:56
【问题描述】:
所以我试图从日期列表中查找最新日期,但我不断收到 NumberFormatException。有没有办法解决这个问题?
import java.util.*;
public class Date
{
private String date;
private int day;
private int month;
private int year;
public Date(String date)
{
String [] newDate = date.split(" ");
this.day = Integer.parseInt(newDate[0]);
this.month = Integer.parseInt(newDate[1]);
this.year = Integer.parseInt(newDate[2]);
}
public boolean isOnOrAfter(Date other)
{
if(this.day < other.day)
{
return true;
}
else if(this.day == other.day && this.month < other.month)
{
return true;
}
else if(this.day == other.day && this.month == other.month && this.year < other.year)
{
return true;
}
return false;
}
public String toString()
{
return day + "/" + month + "/" + year;
}
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many dates: ");
int num = in.nextInt();
System.out.println("Enter " + num + " dates: ");
String [] dates = new String[num];
for(int i = 0; i < dates.length; i++)
{
dates[i] = in.nextLine();
}
Date latest = new Date(dates[0]);
for(int i = 0; i < dates.length; i++)
{
Date newDates = new Date(dates[i]);
if(latest.isOnOrAfter(newDates))
{
latest = newDates;
}
}
System.out.println(latest);
}
}
我认为这只是一个小问题,但我似乎无法找到它。提前致谢。
我有一个检查最新日期的方法,代码的逻辑对我来说似乎很好,如果您发现逻辑中有任何问题,请告诉我。
日期将一次输入一行,例如:
1 1 1890
1 1 2000
2 1 2000
30 12 1999
输出应该是 2/1/2000。
【问题讨论】:
-
你还没告诉你输入了什么?
-
您在
String date中收到的示例? -
抱歉刚刚添加了它
-
该问题要求您创建自己的日期类。很抱歉应该提到这一点。
-
您的核心逻辑仍然存在错误。您必须按此顺序进行比较 - 年、月和日。但你正在做相反的事情。以这两个日期为例 - 1990 年 1 月 2 日和 1880 年 1 月 5 日 - 尝试用这个来调试你的代码
标签: java numberformatexception