View Single Post
Old 09-28-2007, 11:53 AM   #26 (permalink)
slitz
euro scum
 
slitz's Avatar
 
Join Date: Aug 2002
Location: Sweden
Posts: 819
-9 Internets
Quote:
Originally Posted by Kuriin View Post
Write a java program that asks the user for a date and reads th date entered by the user and finally prints a friendly message.

Would this be...?

import java.util.Scanner;
public class Date
{
public static void main(String [] args);
Scanner keyboard = new Scanner(System.in);
string = Date

System.out.println("Please enter today's date.");
Date = keyboard.nextString();
System.out.println("Today's date is:" + mm/dd/yyyy);
System.out.println("Have a nice day.");
}
}

Okay, now that I look at it...I'm doing something wrong, but I can't put my finger on it. Please help.


edit: Just to clarify...what I'm wanting help with is the date and the string index and all that shit. :P
First of all, since there is two classes in the Java API that is named Date already, try to refrain from naming your class Date (this goes for naming all your classes actually. Just stay away from commonly used words)
You should also stay away from writing code in your main method, except for initialization, because it's there for just that, initialization of your program, nothing else (guess you'll understand that when covering static methods/variables).

Anyhoo:
Code:
public class MyCustomDate { private Scanner scanner; private SimpleDateFormat format; private Date inputDate; private boolean failure =false; public MyCustomDate() { format = new SimpleDateFormat("MM/dd/yyyy"); } public void readMyConsole(){ scanner = new Scanner(System.in); String input = scanner.next(); inputDate = null; try { inputDate = format.parse(input); } catch (ParseException ex) { failure = true; } if (!failure){ System.out.println("You entered: " +inputDate.toString()); System.out.println("Current date is: " +new Date()); }else{ System.err.println("wrong format, try again!"); failure = false; readMyConsole(); } } public static void main(String[] args) { MyCustomDate customDate = new MyCustomDate(); customDate.readMyConsole(); } }
Check the API for SimpleFormatDate and Date so you understand what happens.
Perhaps it's a bit of a overkill for your program however, I really don't know, but when using dates one should use the class Date and not a String representation of it and thus this will be a more correct program.

Last edited by slitz : 09-28-2007 at 12:07 PM.
slitz is offline   Reply With Quote

 
Uberguilds Network