Write a class DateSwitcher with a single main method. Inside main, write code th
ID: 3629441 • Letter: W
Question
Write a class DateSwitcher with a single main method. Inside main, write code that, given a local String variable containing a date of the form "2/7/2009", parses each field and prints out the date in the alternative format "2009/2/7". Use System.out.printf() or String.format() to print the date with leading zeroes in the month and day fields: "2009/02/07"
If the String does not contain a /, do not try to parse the String but do print out an error message. Check out the String documentation if necessary.
Explanation / Answer
class DateSwitcher()
{
publicstatic void main(String[]args)
{
String date ="2/7/2009";
int month =Integer.parseInt(date.substring(0,date.indexOf("/")));
date = date.substring(date.indexOf("/")+1);
int day =Integer.parseInt(date.substring(0,date.indexOf("/")));
date = date.substring(date.indexOf("/")+1);
int year =Integer.parseInt(date);
System.out.println(String.format("%04d",year)+"/"+String.format("%02d",day)+"/"+String.format("%02d",month));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.