Charles Bell
Posts: 519
Nickname: charles
Registered: Feb, 2002
|
|
Re: Date
|
Posted: Feb 3, 2003 3:42 PM
|
|
The string a user can enter from the keyboard can have many different formats.
You may want to prompt the user, with an example of the format you have programmed your application for.
import java.io.*;
public class Test{
public Test(){
}
public static void main (String[] args){
Test test = new Test();
String dateString = test.getDateString();
if (test.validateDateString(dateString)){
System.out.println(dateString);
}else{
System.out.println("Invalidate date entered.");
}
}
public String readConsoleInput(){
String lineRead = "";
try{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
lineRead = br.readLine();
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
return lineRead;
}
public String getDateString(){
String lineRead = "";
try{
System.out.println("Enter Date: MM-DD-YYYY");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
lineRead = br.readLine();
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
return lineRead;
}
public boolean validateDateString(String dateString){
int month = toInt(getMonth(dateString));
int day = toInt(getDay(dateString));
int year = toInt(getYear(dateString));
System.out.println("Month: " + month);
System.out.println("Day: " + day);
System.out.println("Year: " + year);
return ((month > 0) && (month <= 12)
&& (day > 0) && (day <= 31)
&& (year > 0) && (getYear(dateString).length() == 4));
}
private String getMonth(String dateString){
String month = "";
if (dateString.indexOf("-") > 0) month = dateString.substring(0,dateString.indexOf("-"));
return month;
}
private String getDay(String dateString){
String day = "";
if (dateString.indexOf("-") > 0) day = dateString.substring(dateString.indexOf("-") + 1,dateString.lastIndexOf("-"));
return day;
}
private String getYear(String dateString){
String year = "";
if (dateString.indexOf("-") > 0) year = dateString.substring(dateString.lastIndexOf("-")+1);
return year;
}
private int toInt(String s){
int n = -1;
try{
n = Integer.parseInt(s);
}catch(NumberFormatException nfe){
System.err.println(s + " is not a valid integer.");
}
return n;
}
}
This has an output which looks like: Enter Date: MM-DD-YYYY 12-22-2003 Month: 12 Day: 22 Year: 2003 12-22-2003
|
|