Philipp Philipp - 3 months ago 21
Java Question

Java Month Mapping Program

Hey guys I am supposed to write a Java code that is able to print the month name to the corresponding month number and the other way around... if the input is invalid the programm should just print an error message. Other requirements are the switch statement and a static class method boolean to determine the type of input. Unfortunately I have no idea how to determine the data type and how to use the switch statement for strings... Thats what I've done so far, it works for the first part:

import java.util.Scanner;

public class MonthMapping{

public static boolean isMonthNumber(String month) {

int monthnumber = Integer.parseInt(month);

if((monthnumber >= 1) && (monthnumber <= 12)) {
return true;
}

else {
return false;
}
}

public static void main(String [] args){

Scanner sc = new Scanner(System.in);


System.out.print("Enter month: ");
int month = sc.nextInt();

String monthString;

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

System.out.println(monthString);

}


}


Can anybody give me a solution for the second part? Or at least some hints how to do it?

Answer

Checking Data type

You can create methods like the following to check what the input type is:

public static boolean isString(Object input){
    try{
        String str = (String) input;
        return true;
    }catch(ClassCastException ex){
        return false;
    }
}

Consider the following cases:

Input: false, Output: (false will be returned)

Input: "January", Output: (true will be returned)

Input: 43 , Output: (false will be returned)

False is returned because the cast does not work, a ClassCastException is thrown when that exception is thrown it is caught by the catch clause which captures exceptions of the type Exception & it's respective subclasses, this is why false is returned.

When the Class Cast is successful true is returned as with the second case.


Switch statements with Strings

The switch statements is used in a similar way to you have already used it, however the datatypes have changed to... Strings, as you would have assumed.

switch(/*Enter String to be tested*/){

case /*String 1*/: //Logic if String to be tested is equal to logic 1.
                   //Optional break statements.
case /*String 2*/: //Logic if String to be tested is equal to logic 2.
                   //Optional break statements.
default: //Logic if the String to be tested is not equal to any of the case strings.
Comments