简体   繁体   English

作业的左侧必须是变量Error

[英]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. 我只想帮助您理解错误,该错误似乎发生在最后的else语句中。

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");
    }
}

You need to remove the else condition. 您需要删除else条件。 Only else if can have condition. 只有其他情况才能有条件。 You can also change the last else to else if. 您也可以将其他的if更改为else。

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 另外,不要将字符串与==进行比较,您应该使用.equals更多详细信息, 请点击此处

EG: 例如:

X.equals(Birth[0])

Here: 这里:

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

should be 应该

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

Besides == should not be used instead of equals method. 此外, ==不能代替equals方法。 I'm just answering about the cause of Left hand side of an assignment must be a variable error. 我只是在回答作业左手的原因一定是变量错误。

Else don't have condition checking part. 否则没有条件检查部分。 Remove () in front of else. 删除其他前面的()

Or 要么

Use another ladder of else if simply put if before braces. else if放在括号前,只需放其他梯子即可。

And other than logic use X.equals("some value") to compare values rather == compares references. 除逻辑外,还使用X.equals("some value")比较值,而不是==比较引用。

应该等于

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

You don't need to specify the condition for the last condition in an if...else ladder. 您无需在if ... else阶梯中为最后一个条件指定条件。 You can either use else if (condition) or just the else. 您可以使用else if(条件),也可以仅使用else。

You are getting the error as your syntax is wrong by using else (condition). 通过使用else(条件),您的语法错误,您将得到错误。 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. 另外,在比较两个字符串的原始内容时,应始终使用equals()方法检查两个字符串是否相等。 It compares the values of string for equality. 它比较字符串的值是否相等。 Hence, in your case it should be - X.equals(Birth[2]) 因此,在您的情况下,应为-X.equals(Birth [2])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM