为什么我会收到“错误:'其他'没有'如果'”?

时间:2014-01-12 05:12:49

标签: java if-statement

我无法在此找到错误:

import java.util.Scanner;

public class StringExample {
  public static void main(String[] args) {
    Scanner myScanner = new Scanner(System.in);

    System.out.println("What's your favorite type of food?");
    System.out.println("1. Pizza?");
    System.out.println("2. Steak?");
    System.out.println("3. Cake?");

    String answer = myScanner.next();
    if (answer.equals ("Pizza")) {
      System.out.println("It's pretty nice, isn't it?");
    }else if (answer.equals ("Steak")); {
      System.out.println("Yummy :)");
    }else if (answer.equals ("Cake")); {
      System.out.println("THE CAKE IS A LIE!");
    }
    }
  }
  

错误:'else'没有'if'

我在第17行收到此错误:

}else if (answer.equals ("Cake")); {

8 个答案:

答案 0 :(得分:11)

删除这些行后的;

}else if (answer.equals ("Steak"))
...
}else if (answer.equals ("Cake"))

设置;会告诉else if正文是空的。

从此site

  

分号告诉'if语句'在放置时什么都不做   直接在它之后。换句话说:如果陈述是真的,请执行:';'   (无)

答案 1 :(得分:3)

在这两个陈述之后删除分号

else if (answer.equals ("Steak"));
else if (answer.equals ("Cake"));

答案 2 :(得分:2)

public class StringExample {
  public static void main(String[] args) {
    Scanner myScanner = new Scanner(System.in);

    System.out.println("What's your favorite type of food?");
    System.out.println("1. Pizza?");
    System.out.println("2. Steak?");
    System.out.println("3. Cake?");

    String answer = myScanner.next();
    if (answer.equals ("Pizza")) {
      System.out.println("It's pretty nice, isn't it?");
    }else if (answer.equals ("Steak")) {
      System.out.println("Yummy :)")
    }else if (answer.equals ("Cake")) {
      System.out.println("THE CAKE IS A LIE!");
    }
    }
  }

在if或else if条件之后,不应使用分号。

答案 3 :(得分:1)

删除所有不需要的;

if (answer.equals ("Pizza")) {
  System.out.println("It's pretty nice, isn't it?");
}else if (answer.equals ("Steak")) {
  System.out.println("Yummy :)")
}else if (answer.equals ("Cake")) {
  System.out.println("THE CAKE IS A LIE!")
}

答案 4 :(得分:0)

可能有两件事:

1 你不是指分号

2 您'意外'删除了与if一起发布的else

答案 5 :(得分:0)

检查此行,你有一个分号(;)。

}else if (answer.equals ("Steak")); {

and 

}else if (answer.equals ("Cake")); {

使用

}else if (answer.equals ("Steak")) {

}else if (answer.equals ("Cake")) {

答案 6 :(得分:0)

你已经放了一些不必要的东西;在else if语句后面标记,删除它。

if-else if语句如下所示

if ( condition )
{ result }
else if( condition )
{ result }
else if( condition )
{ result }
else { result }

答案 7 :(得分:0)

错误原因:
          因为';'你包括的符号。把这个符号想象成一个终止字符。所以即使在if之前,如果输入了块,它也将被终止。它让else if if为空,这就是编译器搜索else语句的原因

正确的方式:

if (answer.equals ("Pizza")) {
  System.out.println("It's pretty nice, isn't it?");
}else if (answer.equals ("Steak")) {
  System.out.println("Yummy :)")
}else if (answer.equals ("Cake")) {
  System.out.println("THE CAKE IS A LIE!")
}

这会对你有所帮助