Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 621
user1740066 Avatar asked Nov 29 '22 16:11

user1740066


1 Answers

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.

like image 98
Óscar López Avatar answered Dec 05 '22 04:12

Óscar López