错误:'else'没有'if' [英] Error: 'else' without 'if'
问题描述
获取不带if语句的else:
Getting an else without if statement:
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");
}
}
我需要使用级联,如果这就是为什么它看起来像那样。另外,如果我正确地进行了级联,你能告诉我吗?我无法找到一个很好的级联示例,如果是这样,我只是在了解级联的含义时尽力而为。
I need to use a cascading if which is why it looks like that. Also, could you please let me know if I did the cascading if correctly? I haven't been able to find a good example of cascading if so I just did my best from knowing what cascading means.
LazyDaysCamp.java:14: error: 'else' without 'if'
else if (temp <= 95)
^
1 error
这是我得到的错误
推荐答案
删除此行末尾的分号:
if (temp > 95 || temp < 20);
请使用大括号! Java与不是类似Python,其中缩进代码会创建一个新的块范围。最好安全地使用它并且总是使用大括号 - 至少在你获得更多使用该语言的经验并准确理解 时你可以省略它们。
And please, please use curly brackets! Java is not like Python, where indenting the code creates a new block scope. Better to play it safe and always use curly brackets - at least until you get some more experience with the language and understand exactly when you can omit them.
这篇关于错误:'else'没有'if'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!