Left hand side of an assignment must be a variable Error

Please don't mind the logic of the code; I just want help understanding the error, which seems to occur at the last else statement.

package day1.samples;
import java.util.Scanner;

public class Horscope {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String [] Birth={"January","February","March"};
    System.out.println("Please Enter Your BirthMonth");
    Scanner input =new Scanner(System.in);
    String X;
    X=input.nextLine();
    if (X==Birth[0]) {
        System.out.println("Your Horoscope is Gemini");
    } else if(X==Birth[1]) {
        System.out.println("your Horscope is libra");
    } else (X==Birth[2]) {
        System.out.println("Your horscope is Leo");
    }
}

Upvotes: 1

Views: 1683

Answers (5)

StackFlowed
StackFlowed

Reputation: 6816

You need to remove the else condition. Only else if can have condition. You can also change the last else to else if.

X=input.nextLine();
if (X.equals(Birth[0])) {
    System.out.println("Your Horoscope is Gemini");
} else if(X.equals(Birth[1])) {
    System.out.println("your Horscope is libra");
} else {
    System.out.println("Your horscope is Leo");
}


Also you don't compare strings with == you should use .equals more details click here

EG:

X.equals(Birth[0])

Upvotes: 3

Ameya Pandilwar
Ameya Pandilwar

Reputation: 2778

You don't need to specify the condition for the last condition in an if...else ladder. You can either use else if (condition) or just the else.

You are getting the error as your syntax is wrong by using else (condition). Hope this helps.

Also, you should always use the equals() method to check if two strings are equal as it compares the original content of the string. It compares the values of string for equality. Hence, in your case it should be - X.equals(Birth[2])

Upvotes: 0

Sindhoo Oad
Sindhoo Oad

Reputation: 1194

Else don't have condition checking part. Remove () in front of else.

Or

Use another ladder of else if simply put if before braces.

And other than logic use X.equals("some value") to compare values rather == compares references.

Upvotes: 1

hata
hata

Reputation: 12478

Here:

} else (X==Birth[2]) {

should be

} else if (X==Birth[2]) {

Besides == should not be used instead of equals method. I'm just answering about the cause of Left hand side of an assignment must be a variable error.

Upvotes: 1

ergonaut
ergonaut

Reputation: 7057

It should be .equals

  } else if (X.equals(Birth[2])) {

Upvotes: 1

Related Questions