So I'm trying to find the latest date from a list of dates, but I keep getting a NumberFormatException. Is there any way of resolving this?
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);
}
}
I think its just a tiny problem, but I can't seem to find it. Thanks in advance.
I have a method that checking for the latest date, the logic of the code seems fine to me, if you see any problems in the logic, let me know.
The dates will be input one line at a time, for example:
1 1 1890
1 1 2000
2 1 2000
30 12 1999
The output should be 2/1/2000.