0

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?

Martin G
  • 17,357
  • 9
  • 82
  • 98
Philipp
  • 57
  • 1
  • 8

2 Answers2

1

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.
RamanSB
  • 1,162
  • 9
  • 26
0

I realize you are likely doing homework or practice coding, and so be it. But you should know this exact behavior is already built into the java.time classes.

java.time.Month

Among those classes is the Month enum, defining a dozen objects, one for each month in the year, January-December, numbered 1-12.

Get a Month object for a particular month number (1-12).

Month month = Month.of( 2 );  // 2 → February.

Going the other direction, ask a Month object for its month number.

int monthNumber = Month.FEBRUARY.getValue();  // February → 2.

Many other handy methods on this class, such as knowing the number of days in each month. The class can even generate a localized name of the month.

Also, you should pass objects of this enum around your code base rather than mere integer numbers. Doing so provides type-safety, ensures a valid range of values, and makes your code more self-documenting. See Oracle Tutorial if unfamiliar with the surprisingly powerful enum facility in Java.

You also may find useful the Year and YearMonth classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154