Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

java - Error: 'else' without 'if'

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

That's the error I'm getting

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Remove the semicolon at the end of this line:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...