Reputation: 141
I have a long if statements in my program and I was wondering if there was a way to simply continue the conditional onto the next line so that it doesn't stretch off forever.
Here's my statement:
if (Character.isDigit(enrollDate.charAt(0)) && Character.isDigit(enrollDate.charAt(1)) && Character.isDigit(enrollDate.charAt(3)) && Character.isDigit(enrollDate.charAt(4)) && Character.isDigit(enrollDate.charAt(6)) && Character.isDigit(enrollDate.charAt(7)) && Character.isDigit(enrollDate.charAt(8)) && Character.isDigit(enrollDate.charAt(9)))
I'm just trying to ensure that a string containing a date is of the format I specified.
Upvotes: 2
Views: 3973
Reputation: 106450
As suggested above, you can definitely break out your if
into multiple lines.
However...
The format that you're working with smells like this:
\d\d[-/]\d\d[-/]\d\d\d\d
That is, you have any two numbers preceding a dash or slash, followed by two other numbers preceding a dash or slash, followed by four numbers.
I'm 99% sure that this is a date of some kind.
If that's the case, then there's an easier way to do this: DateFormat#parse
.
parse
may throw a ParseException
, so you could either hard-wire it into the method...
public static void main(String[] args) throws ParseException {
DateFormat fmt = new SimpleDateFormat("mm-dd-yyyy");
System.out.println(fmt.parse("03-30-2014"));
}
...or write a try-catch block around it.
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("mm-dd-yyyy");
try {
System.out.println(fmt.parse("03-30-2014"));
} catch (ParseException e) {
e.printStackTrace();
}
}
The latter may give you a chance to recover from a disastrous parsing attempt.
Upvotes: 2
Reputation: 178
I agree with Marco, yes you can use multiple lines, but you need to improve this condition. Is it enrollDate is a string? You could use int tryparse for the hole string instead of verifing each char.
Upvotes: 0
Reputation: 14847
Yes.
But why not just try it?
if (
Character.isDigit(enrollDate.charAt(0)) &&
Character.isDigit(enrollDate.charAt(1)) &&
Character.isDigit(enrollDate.charAt(3)) &&
Character.isDigit(enrollDate.charAt(4)) &&
Character.isDigit(enrollDate.charAt(6)) &&
Character.isDigit(enrollDate.charAt(7)) &&
Character.isDigit(enrollDate.charAt(8)) &&
Character.isDigit(enrollDate.charAt(9))
)
Anyway, you could try to improve this if
Upvotes: 3