Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads a string for a date in the format month / day / year

ID: 3637483 • Letter: W

Question

Write a program that reads a string for a date in the format month / day / year and displays it
in the format day . month . year, which is a typical format used in Europe. For example, if the
input is 06/17/08, the output should be 17.06.08. Your program should use JOptionPane for
input and output.
Note - Your program should create an output string from the input string and should include
the following lines with appropriate Java statements at “…”
________________________________________________________________________
import javax.swing.JOptionPane;
public class DateDisplayer
{
public static void main(String[] args)
{
String dateString = JOptionPane.showInputDialog(
"Enter a date in the format month/day/year . " +
"I will output the date in the format
day.month.year ");
String day, month, year;

dateString = dateString.trim();
int delimiter = dateString.indexOf("/");
month = dateString.substring(…);

//System.out.println("index is " + delimiter);
//System.out.println("Month is " + month);

String rest = dateString.substring(…).trim();
//System.out.println("Rest is " + rest);

delimiter = rest.indexOf("/");
day = rest.substring(…);

//System.out.println("index is " + delimiter);
//System.out.println("day is " + day);

year = rest.substring(…).trim();
//System.out.println("year is " + year);

JOptionPane.showMessageDialog(null, dateString +
" converts to: " + day + "." + month + "." + year);
System.exit(0);
}
}

Explanation / Answer

dateString = dateString.replace('/', '.'); char[] buffer = dateString.toCharArray(); char temp; temp = buffer[0]; buffer[0] = buffer[3]; buffer[3] = temp; temp = buffer[1]; buffer[1] = buffer[4]; buffer[4] = temp; dateString = new String(buffer); There is probably a more elegant and correct way of doing this which works even on dates such as "6/17/08". Maybe using regular expressions? Edit: Here is the magical regex solution. dateString = dateString.replaceAll( "([0-9]+)/([0-9]+)", "$2/$1"); // swap date and month dateString = dateString.replace('/', '.'); // replace slashes with dot

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote