1

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");
    }
}
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • 2
    And for your next question, please see [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – rgettman Oct 08 '15 at 19:47
  • Your last `else` statement is followed by a condition. The format of if - else statement should be like `if (condition1) {...} else if (condition2) { } else if (condition3) else if (condi...)... else {} ` – NaNey Oct 08 '15 at 19:49

5 Answers5

3

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])
Community
  • 1
  • 1
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
1

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.

hata
  • 11,633
  • 6
  • 46
  • 69
1

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.

Sindhoo Oad
  • 1,194
  • 2
  • 13
  • 29
1

It should be .equals

  } else if (X.equals(Birth[2])) {
ergonaut
  • 6,929
  • 1
  • 17
  • 47
0

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])

Ameya Pandilwar
  • 2,638
  • 28
  • 28