Khalid :
Write a program that takes as input a date in the form mm/dd/yyyy and prints out the same date in the form dd-Month-yy
. For example, if the user inputs 5/31/2011
then the program outputs 5-May-11
There are two challenges to this program:
- You need to read in the data and separate the parts (month, day, year)
- You need to decide which word to print – this part is the selection structure
For the first challenge, try the following algorithm:
- Read the input as a String
- Assign the substring that starts at the beginning of the String and ends with the first ‘/’ to a variable representing the month.
- Using the substring that starts after the first ‘/’ assign the substring that starts at the beginning (of the day) and ends with the second ‘/’ to a variable representing the day
- Assign the rest of the String (after the second ‘/’) to a variable representing the year
For the second challenge, you’ll use a selection structure that picks the word to print based on the value of the month variable.
Here's my code:
import java.util.Scanner;
public class DateConverter {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String date;
System.out.println("Please enter a date in the form mm/dd/yyyy");
date = kb.nextLine();
String day = date.substring(3,5);
String month = date.substring(0,2);
String year = date.substring(6,date.length());
int conv = Integer.parseInt(month);
if (conv == 1){
System.out.println(day + "-January-" + year);
}
else if (conv == 2){
System.out.println(day + "-February-" + year);
}
else if (conv == 3){
System.out.println(day + "-March-" + year);
}
else if (conv == 4){
System.out.println(day + "-April-" + year);
}
else if (conv == 5){
System.out.println(day + "-May-" + year);
}
else if (conv == 6){
System.out.println(day + "-June-" + year);
}
else if (conv == 7){
System.out.println(day + "-July-" + year);
}
else if (conv == 8){
System.out.println(day + "-August-" + year);
}
else if (conv == 9){
System.out.println(day + "-September-" + year);
}
else if (conv == 10){
System.out.println(day + "-October-" + year);
}
else if (conv == 11){
System.out.println(day + "-November-" + year);
}
else if (conv == 12){
System.out.println(day + "-December-" + year);
}
else {
System.out.println("Invalid data. try again");
}
}
}
I just need to know how can I assign a substring that starts at the beginning of the string and ends at the first "/" character.
TorchNight MC :
int slashPos = string.indexOf("/");
String substring = string.substring(0, slashPos);
String#indexOf() will provide the index of the first string occurrence.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=238515&siteId=1