# Earlier date

• 02-07-2010, 12:21 AM
ŖàΫ ỏƒ Ңόρę
Earlier date
Hi

I have written the following programe to compare two dates and give the earlier date.

Code:

import java.util.Scanner;

public class Dates {
public static void main(String[] args){

//Declare object of Scanner class
Scanner scan = new Scanner(System.in);

//Declare variables
int d1,m1,y1;
int d2,m2,y2;

//Prompt user to enter the first date
System.out.print("Enter the first date : " );
d1 = scan.nextInt();
m1 = scan.nextInt();
y1 = scan.nextInt();

//Prompt user to enter the second date
System.out.print("Enter the second date : " );
d2 = scan.nextInt();
m2 = scan.nextInt();
y2 = scan.nextInt();

if ( (d1==d2) && (m1==m2) && (y1==y2)){
System.out.println("Dates are the same !");
}else if (y1<y2){
System.out.println(d1 + "/" + m1 + "/" + y1 + " is earlier than " + d2 + "/" + m2 + "/" + y2);
}else if ((m1<m2)&&(y1==y2)){
System.out.println(d1 + "/" + m1 + "/" + y1 + " is earlier than " + d2 + "/" + m2 + "/" + y2);
}else if ((d1<d2)&&(m1==m2)&&(y1==y2)){
System.out.println(d1 + "/" + m1 + "/" + y1 + " is earlier than " + d2 + "/" + m2 + "/" + y2);
}else{
System.out.println(d2 + "/" + m2 + "/" + y2 + " is earlier than " + d1 + "/" + m1 + "/" + y1);
}
}
}

First, How can I make the user input the date as (dd mm yyyy) instead of write the day in one line and the month in another line and the year in anther line.

Second, Do you think my code is right and gives the earlier date or not?

Thanks
• 02-07-2010, 12:29 AM
Fubarable
Quote:

Originally Posted by ŖàΫ ỏƒ Ңόρę
First, How can I make the user input the date as (dd mm yyyy) instead of write the day in one line and the month in another line and the year in anther line.

Look at using String's split method, in particular split(" ") if you want to split on spaces. For example "31 12 1979".split(" ") will return a three item String array consisting of the three Strings.

Quote:

Second, Do you think my code is right and gives the earlier date or not?
The best way to answer this question is to test your code and find out. :)

Much luck!
• 02-07-2010, 07:01 PM
ŖàΫ ỏƒ Ңόρę
Quote:

Originally Posted by Fubarable
Look at using String's split method, in particular split(" ") if you want to split on spaces. For example "31 12 1979".split(" ") will return a three item String array consisting of the three Strings.

So, I have to use an array !

Thank u

best regards
• 02-07-2010, 07:04 PM
JosAH
Quote:

Originally Posted by ŖàΫ ỏƒ Ңόρę
So, I have to use an array !

Also have a look at the SimpleDateFormat class.

kind regards,

Jos