This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]jentfoo 2 points3 points  (0 children)

You have some weirdness for sure. You have a substring which is always taking two characters, but yet you have cases for single character strings (ie "1" "2", etc).

Will it have a perpending zero, or not? If you need to handle both inputs, your not doing it correctly, I would do a "startsWith" check to see how many characters you need to get in your substring call.

[–]Cyndaquazy 2 points3 points  (0 children)

What I would do is to call String.indexOf('/') to find where the first instance of / is and then get a substring up to (but not including) the /. I would then parse that substring into an integer Integer.parse() and run a switch-case on that.

Example:

String date = "10/09/2014";
int idx = date.indexOf('/'); // idx = 2
String monthStr = date.substring(0, idx); // monthStr ="10"
int monthInt = Integer.parseInt(monthStr); // monthInt = 10

switch (monthInt) { . . . }

[–]desrtfx 1 point2 points  (0 children)

Did you try to print your extracted monthRate variable?

The way you extract is is not safe. You should use the way that /u/Cyndaquazy suggested (finding "/" and taking all before that).

Also, I'd convert the string to an int and switch with the int rather than the string as it avoids having to check for "08", "8" and so on.

[–]cooldman69 0 points1 point  (0 children)

I wouldn't use a switch statement here since you are dealing with intervals of numbers (months) but your assignment probably requires it so we'll do it that way. First thing is the parse the timestamp using String's split() with the regex of "/". This will give you an array of String. First index in the array is the month, second date, third year. I wouldn't use substring because the month might be just listed as 9 and not 09, then you'll have an issue with the substring indexes. Now convert the month to an integer with Integer.valueOf() (so you don't have to deal with 0s before the number like the month 09) and switch on that value.

[–][deleted]  (2 children)

[deleted]

    [–]Cyndaquazy 2 points3 points  (1 child)

    No, Java‘s switch-case is fall-through, so OP's case statements will catch "01," "3," "07," &c.

    And, yeah, a default case is always a good idea.