错误:'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
这是我得到的错误
推荐答案
去掉这一行末尾的分号:
Remove the semicolon at the end of this line:
if (temp > 95 || temp < 20);
请使用大括号!Java 不像 Python 那样,在 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屋!