0

I'm trying to get this switch statement to work.

I ask for the user's birthday and they put it in the format DD.MM.YYYY. The if statement determines if they use the "." to separate it or one of my other symbols such as "/", " ". The other symbols work fine, they enter the switch statement so if the user enters 15/07/1993 it will work fine and the month becomes July. But when they enter 15.07.1993 it goes to the default case not the 7th case.

I assume it has got do with the escaped "."

("\\.")

This might be changing the value of it. Is there any way around it? input is my scanner.

Any questions feel free to ask.

if(input.contains("\\."))
{
    String[] tokens = input.split("\\.");
    day = Integer.parseInt(tokens[0]);
    intMonth = Integer.parseInt(tokens[1]);
    year = Integer.parseInt(tokens[2]);
}

switch(intMonth)    
{       
    case 1: month = "January";
        break;  
    case 2: month = "Febuary";
        break;
    case 3: month = "March";
        break;
    case 4: month = "April";
        break;
    case 5: month = "May";
        break;
    case 6: month = "June";
        break;
    case 7: month = "July";
        break;
    case 8: month = "August";
        break;
    case 9: month = "September";
        break;
    case 10: month = "October";
        break;
    case 11: month = "November";
        break;
    case 12: month = "December";
        break;  
    default: month = "not valid";
        break;              
}
4

1 回答 1

1

The problem is that you use a regular expression for String.contains.

According to the method documentation, you need to supply a CharSequence to String.contains, ie. you have to write if (input.contains(".")) instead of if (input.contains("\\.")).

于 2013-08-08T06:57:43.047 回答