-5

I've been fiddling with this for a bit but I can't get it to run. Everything works except for the last section where I want it to give the month as a number. Is there a better way to do this? What I'm getting is that, whenever I run the program, the section where I want it to give me the number month always gives me the else value of 0. Yes, I know I can use a switch, and I have a version that works completely fine as a switch, but I need it to work as an if/else.

Is there anything I can do in this case?

import java.util.Scanner;

public class Months {

    static Scanner userInput = new Scanner(System.in);

    public static String idString(){

         return "Months, Kain R, csscXXXX";

    }

    public static void main(String[] args) {

        System.out.println("Enter the month:");

        String userMon = userInput.nextLine();

        if (userMon.charAt(0) > 90 ) {
            userMon = userMon.substring(0,1).toUpperCase() + userMon.substring(1);
        }

        else {
            userMon = userMon;
        }

        System.out.println("You entered " + userMon);

        userMon = userMon.substring(0, 3).toUpperCase();


        System.out.println("Its abbreviation is " + userMon);


        if (userMon == "JAN") {
            userMon = "1";
        }
        else if (userMon == "FEB") {
             userMon = "2";
        }
        else if (userMon == "MAR") {
            userMon = "3";
        }
        else if (userMon == "APR") {
            userMon = "4";
        }
        else if (userMon == "MAY") {
            userMon = "5";
        }
        else if (userMon == "JUN") {
            userMon = "6";
        }
        else if (userMon == "JUL") {
            userMon = "7";
        }
        else if (userMon == "AUG") {
            userMon = "8";
        }
        else if (userMon == "SEP") {
            userMon = "9";
        }
        else if (userMon == "OCT") {
            userMon = "10";
        }
        else if (userMon == "NOV") {
            userMon = "11";
        }
        else if (userMon == "DEC") {
            userMon = "12";
        }
        else {
            userMon = "0";
        }


        System.out.println("This is month number " + userMon);
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Kain R
  • 1
  • [How to compare Strings in Java](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) and you might consider using a `Map` of some kind to map between the `String` and the resulting value – MadProgrammer Feb 27 '18 at 04:48

1 Answers1

1

In Java, for comparing two String objects, you must use the method "equals". If you use ==, you are comparing their references, which are different.

Always place the literal at the front to avoid NullPointersExceptions.

if ("JAN".equals(userMon)) {
    userMon = "1";
}
Pang
  • 9,564
  • 146
  • 81
  • 122
jonhid
  • 2,075
  • 1
  • 11
  • 18