Incompatible types - found java.lang.String but expected int

Yes, I thought this was an easy task, and yes, I’m new to the Java world, but I can’t get this code to work as expected :slight_smile: The compiler says “incompatible types - found java.lang.String but expected int” at the switch line, but I don’t understand why (I mean, names is declared to contain strings which is also does, and I’m only referencing it in the switch line?). Anyone?

public class Switch {
    public static void main(String[] args) {
        String[] names = {"Espen", "Daniel", "Peter", "Sam"};

        for (int i = 0; i < names.length; i++) {
            switch(names[i]) {
                case "Espen" :
                case "Daniel" :
                    System.out.println("Espen or Daniel");

                case "Peter" :

                case "Sam" :

Nevermind. I solved the problem.

switch does not allow Strings, that’s the problem. You can only use int or char, or types that can be converted to int (like short, long, maybe float gets truncated, not exactly sure). Unfortunately for this you’ll need an ugly looking if () else if () else if () else … oh it is ugly… The case would look nicer.

Also since you’re new to Java I’ll remind you to use String.equals to compare and not == since a lot of beginners make that mistake.

It is ugly indeed, but I guess I’ll just have to get used to the small differences between Java and PHP.

And thanks for the tip – didn’t know that.