Hey, This is just a simple exercise from class that I decided to have a go at putting an exception in. According to the book input for this problem is supposed to be in the following format: APRIL 19, 2009 What I'm trying to do with my exception is make sure the user(whoever grades it) follows those parameters so my program works. Does this look ok? Could I have done anything better?
Edit: Thanks for the timely answers! I know I have a lot to learn but hopefully one day I'll be capable enough to answer questions on here. cheers
import jpb.*;
public class ConvertDate {
public static void main(String[] args) {
try{
SimpleIO.prompt("Enter date to be converted: ");
String bam = SimpleIO.readLine();
bam = bam.trim().toLowerCase();
//empty space is taken off both ends and the entirety is put in lower case
int index1 = bam.indexOf(" ");
int index2 = bam.lastIndexOf(" ");
int index3 = bam.indexOf(",");
/*critical points in the original string are located using indexing to divide and conquer
in the next step*/
String month = bam.substring(0,index1);
String up = month.substring(0, 1).toUpperCase();
String rest = month.substring(1,index1);
String day = bam.substring(index1, index3).trim();
String year = bam.substring(index2+1);
//now all the pieces are labeled and in their correct cases
System.out.println("Converted date: " +day +" " +up +rest +" " +year);
//everything comes together so perfectly
} catch(StringIndexOutOfBoundsException e){
System.out.println("best type that in like the book does on page 125...");}
}
}
Here are a few thoughts. These are just my opinion, so take them with a grain of salt or ignore completely if you wish:
import statement is doing, but it's possible to do all this without introducing the dependency on the library. You should be aware of the effect that dependencies have.Here's how I might write the same thing:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class ConvertDate
{
private static final DateFormat DEFAULT_FORMAT;
static
{
DEFAULT_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
DEFAULT_FORMAT.setLenient(false);
}
public static void main(String[] args)
{
for (String dateString : args)
{
try
{
Date date = DEFAULT_FORMAT.parse(dateString);
System.out.println(date);
}
catch (ParseException e)
{
System.out.println("invalid date string: " + dateString);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With