How to fix 'Incompatible types' error when converting String to int in Java?

82 Views Asked by At

I'm teaching myself java and I came across this error. I'm trying to enter a number of a month and I have to use a switch case to return the "answer". I get the follow error:

package javauebung5;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Type Number for name of month");
        int monthNumber = scanner.nextInt();

        monthNumber = determineNameofMonth(monthNumber);
    }

    private static String determineNameofMonth(int monthNumber) {
        switch (monthNumber) {
            case 1: return "January";

            case 2: return "February";

            case 3: return "March";

            case 4: return "April";

            case 5: return "May";

            case 6: return "June";

            case 7: return "July";

            case 8: return "August";

            case 9: return "September";

            case 10: return "October";

            case 11: return "November";

            case 12: return "December";

        }
        return "Invalid Month";
    }
}

This is the error:

Incompatible types. Found: 'java.lang.String', required: 'int'

2

There are 2 best solutions below

2
Arfur Narf On
 monthNumber = determineNameofMonth(monthNumber);

Per its declaration and intent, determineNameofMonth returns a String. Here you attempt to assign to an integer; the error message is telling you that an integer variable requires an integer value.

Use something like:

 String monthName = determineNameofMonth(monthNumber);

(I assume you'll then want to write code to print out monthName, otherwise you're doing nothing with the result of the computation).

2
rzwitserloot On
int monthNumber = scanner.nextInt();
monthNumber = determineNameofMonth(monthNumber);

monthNumber is a variable. It has been declared to be of type int - and that is for the lifetime of that variable (you can't 're-type' a variable in java). That means monthNumber is guaranteed to never hold anything that isn't an int value, and the compiler will refuse to compile code unless it can be 100% certain that rule holds.

determineNameofMonth(monthNumber) is of type String, because the method determineNameofMonth has been declared as such. String is not an int, so, you can't do this.

Presumably you want:

String monthName = determineNameofMonth(monthNumber);

i.e. make a new variable. The name monthNumber shouldn't hold a name - then the variable is misnamed.

Note that you don't need to do this stuff, java already has Month:

import java.time.Month;

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Type Number for name of month");
    int monthNumber = scanner.nextInt();
    Month m = Month.of(monthNumber);
    System.out.println("You chose: " + m);
}