You will write a Java program that first asks the user for a list of dates, and
ID: 3673045 • Letter: Y
Question
You will write a Java program that first asks the user for a list of dates, and then prints the earliest date and the latest date.
The dates from the user must be stored in an int[][] array. Each row in the array will represent a different date from the list. The first column will represent the month, the second column will represent the day, and the last column will represent the year. For example, in the list of dates above, index [0][1] in your array should be 12. (The 0 means the first date, 3/12/2005, and the 1 means the month for that date -- 12.)
You must use a StringTokenizer to break apart the list of dates and store them in your array.
Explanation / Answer
program:
import java.io.*;
import java.util.StringTokenizer;
import java.util.Scanner;
public class Dates {
public static void main(String[] args)throws IOException
{
int size=0,ed,em,ey;
System.out.println("Enter no of dates you want to enter");
Scanner scan=new Scanner(System.in);
size=scan.nextInt();
int[][] dates=new int[size][3];
System.out.println("Enterthe dates in this formate(mm-dd-yyyy)");
for(int i=0;i<size;i++)
{
String date=scan.next();
StringTokenizer st = new StringTokenizer(date,"-");
while (st.hasMoreTokens()) {
dates[i][0]=Integer.parseInt(st.nextToken());
dates[i][1]=Integer.parseInt(st.nextToken());
dates[i][2]=Integer.parseInt(st.nextToken());
}
}
for(int i=0;i<size;i++)
{
for(int j=0;j<3;j++)
System.out.print(dates[i][j]+" ");
System.out.println();
}
ed=dates[0][1];
em=dates[0][0];
ey=dates[0][2];
for(int i=1;i<size;i++)
{
if(dates[i][2]>ey)
{
ed=dates[i][1];
em=dates[i][0];
ey=dates[i][2];
}
else if(dates[i][2]==ey)
{
if(dates[i][0]>em)
{
ed=dates[i][1];
em=dates[i][0];
ey=dates[i][2];
}
else if(dates[i][0]==em)
{
if(dates[i][1]>ed)
{
ed=dates[i][1];
em=dates[i][0];
ey=dates[i][2];
}
}
}
}
System.out.println("Latest Date:"+em+"-"+ed+"-"+ey);
for(int i=1;i<size;i++)
{
if(dates[i][2]<ey)
{
ed=dates[i][1];
em=dates[i][0];
ey=dates[i][2];
}
else if(dates[i][2]==ey)
{
if(dates[i][0]<em)
{
ed=dates[i][1];
em=dates[i][0];
ey=dates[i][2];
}
else if(dates[i][0]==em)
{
if(dates[i][1]<ed)
{
ed=dates[i][1];
em=dates[i][0];
ey=dates[i][2];
}
}
}
}
System.out.println("Earliest Date:"+em+"-"+ed+"-"+ey);
}
}
output:
run:
Enter no of dates you want to enter
3
Enterthe dates in this formate(mm-dd-yyyy)
12-5-1999
5-28-1999
6-12-1999
12 5 1999
5 28 1999
6 12 1999
Latest Date:12-5-1999
Earliest Date:5-28-1999
BUILD SUCCESSFUL (total time: 37 seconds)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.