错误:'其他'没有'如果'

如果没有声明,就得到别的东西

import java.util.Scanner; public class LazyDaysCamp { public static void main (String[] args) { int temp; Scanner scan = new Scanner(System.in); System.out.println ("What's the current temperature?"); temp = scan.nextInt(); if (temp > 95 || temp < 20); System.out.println ("Visit our shops"); else if (temp <= 95) if (temp >= 80) System.out.println ("Swimming"); else if (temp >=60) if (temp <= 80) System.out.println ("Tennis"); else if (temp >= 40) if (temp < 60) System.out.println ("Golf"); else if (temp < 40) if (temp >= 20) System.out.println ("Skiing"); } } 

我需要使用级联,这是为什么看起来像这样。 另外,如果我正确地进行了级联,请让我知道吗? 如果是这样,我一直没能find级联的好例子,我只是尽全力了解级联的含义。

 LazyDaysCamp.java:14: error: 'else' without 'if' else if (temp <= 95) ^ 1 error 

这是我得到的错误

删除该行末尾的分号:

 if (temp > 95 || temp < 20); 

请使用大括号! Java不像Python,缩进代码创build一个新的块范围。 最好是安全地使用花括号 – 至less在你获得更多的语言经验之前,并且确切的理解你何时可以忽略它们。

问题是如果第一个if if (temp > 95 || temp < 20); 使用正常的缩进是一样的

 if (temp > 95 || temp < 20) { } 

也就是说,如果temp不在20和95之间,那么执行一个空的块。 这是没有别的。

否则下一行没有,如果相应的,从而产生你的错误

处理这个问题的最好方法是使用大括号来显示if后执行的内容。 这并不意味着编译器会捕获这些错误,但是首先您通过查看缩进来看到更多的问题,而且这些错误可能看起来更具可读性。 不过,您可以使用诸如eclipse,checkstyle或FindBugs之类的工具来告诉您是否尚未使用或使用空白块。

更好的方法可能是,在重新testing事物时,整理逻辑

 if (temp > 95 || temp < 20) { System.out.println ("Visit our shops"); } else if (temp >= 80) { System.out.println ("Swimming"); } else if (temp >=60) { System.out.println ("Tennis"); } else if (temp >= 40) { System.out.println ("Golf"); } else if (temp >= 20) { System.out.println ("Skiing"); } 

我要为你重新格式化。 如果你使用花括号,你永远不会有这个问题。

 public class LazyDaysCamp { public static void main (String[] args) { int temp; Scanner scan = new Scanner(System.in); System.out.println ("What's the current temperature?"); temp = scan.nextInt(); if (temp > 95 || temp < 20) //<-- I removed the semicolon that caused the error { System.out.println ("Visit our shops"); } else if (temp <= 95) { if (temp >= 80) { System.out.println ("Swimming"); } else if (temp >=60) { if (temp <= 80) { System.out.println ("Tennis"); } else if (temp >= 40) { if (temp < 60) { System.out.println ("Golf"); } else if (temp < 40) { if (temp >= 20) { System.out.println ("Skiing"); } } } } } } }