'Else If' 在 Java 中给出错误“'else'而没有 'if'”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11076846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:41:02  来源:igfitidea点击:

'Else If' giving the error " 'else' without 'if' " in Java

javanetbeansif-statement

提问by Rocmalone

I'm tring to do some Java coding with NETBEANS 7.1.2, but it gives me the error " 'else' without 'if' " when I try to build this code:

我正在尝试使用 NETBEANS 7.1.2 进行一些 Java 编码,但是当我尝试构建此代码时,它给了我错误“'else' without 'if'”:

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    String search1;
    search1 = jTextField1.getText();

    // stone
    if (search1=="Stone" || search1=="Rock" || search1=="stone" || search1=="rock" || search1=="1");
    {
        jTextField2.setText("Stone: 1");

    }

    // grass
    else if (search1=="Grass" || search1=="grass");
    {
        jTextField2.setText("Grass: 2");
    }



}

The problem occurs at the 'else if' under the //grass. Am I doing something wrong?

问题发生在//grass 下的'else if'。难道我做错了什么?

回答by óscar López

In this line:

在这一行:

if (search1=="Stone" || search1=="Rock" || search1=="stone" || search1=="rock" || search1=="1");

And this line:

而这一行:

else if (search1=="Grass" || search1=="grass");

You must remove the ;at the end. Those semicolons are misplaced, the compiler will interpret the first ifstatement as an ifwithout a body, the code between the {}as a block scope and the else ifstatement as an elsewithout an if.

您必须删除;末尾的 。那些分号放错了位置,编译器会将第一条if语句解释为if没有正文,将{}as 块范围和else if语句之间的代码解释为else没有if.

Also, be aware that all the string comparisons are mistaken, in Java you mustuse equals()for comparing two strings for equality, not ==, which compares for identity.

另外,请注意所有字符串比较都是错误的,在 Java 中,您必须使用equals()来比较两个字符串的相等性,而不是==使用身份比较。

回答by Hanon

You have an ";" after the first condition.

你有一个“;” 在第一个条件之后。

The compiler assume this is the end of if statement, therefore the compiler show error at "else if" line. Remove the ";" and it should be fine!

编译器假定这是 if 语句的结尾,因此编译器在“else if”行显示错误。除掉 ”;” 应该没问题!

回答by Irsh Techirsh

I had same problem like what u have. I found this as solution and it worked fine for me. I guess this is what u need.

我有和你一样的问题。我发现这是解决方案,对我来说效果很好。我想这就是你所需要的。

    String unit=jTextField1.getText();
            if(unit.equals("kg") || unit.equals("gm")){
    // some code
            }
else if(unit.equals("dzn")||unit.equals("qty")){
    // some code
        }