简体   繁体   中英

Java calling a method in a switch

so I'm using a getRangedInt method to figure out the user's birth month and date, as well as a Scanner for user input. If they pick February (the prompt asks the user for their birth month number, so 1-12), then I need to change the month's max days to 28 (and so on for the other months with 30 days). I'm trying to use a switch to categorize the months, but when the program is run it simply skips over and the method is never called. The method itself works fine with other examples. What am I missing?

switch (daysInMonth)
    {
        case "1":
        case "3":
        case "5":
        case "7":
        case "8":
        case "10":
        case "12":
            int birthDay = getRangedInt(input,"Enter your birth day: ",1,31);
            break;
        case "2":
            birthDay = getRangedInt(input,"Enter your birth day: ",1,28);
            break;
        case "4":
        case "6":
        case "9":
        case "11":
            birthDay = getRangedInt(input,"Enter your birth day: ",1,30);
    }

If you are reading daysInMonth as an integer then all the test cases will

be false because you are checking for a String value, case "1" checks for a

string "1", while case 1: will check for an integer.

  1. Declare birthDay prior to entering the switch statement. The idea is that you want this value to be set by the time you visit one (and only one) case.

  2. Depending on your definition of daysInMonth you might end up in an unhandled default case or not. You should think about how to define and constrain the switch controlling variable (perhaps with an enum) so you cannot have a default case.

  3. Make sure that daysInMonth is String, and that the .equals() the case is doing does what you expect. I'm not sure what the compile-time errors mismatches like this will raise, but certainly a good IDE will warn you.

Your levels of abstraction are wrong.

You should not call getRangedInt() within a switch. Instead you should have a method called getNumberOfDays() which takes an input that selects a month (which could be a string like "January", "February", or an int, or an enum). That second method can use a switch in it; but you should not switch anywhere else. Reasoning: the knowledge about how many there are in a month should be ONLY in one place. In your solution, you need the very same switch in every place that will be dealing "days per month". Leading to code duplication, which should be avoided at all cost.

Then you call your method getRangedInt() using the return value of that other method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM