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
I am going to reformat this for you. If you use curly brackets, you will never have this problem.
The issue is that the first if
if (temp > 95 || temp < 20);
is the same using normal indentation asThat is if the temp is not between 20 and 95 then execute an empty block. There is no else for this.
The next line else then has no if corresponding to it and thus produces your error
The best way to deal with this is always uses braces to show what is executed after the if. This does not mean the compiler catches the errors but first you are more likely to see any issues by seeing the indentation and also the errors might appear more readable. However you can use tools like eclipse, checkstyle or FindBugs that will tell you if you have not used {} or used an empty block.
A better way might be, sorting out the logic as you are retesting things
Remove the semicolon at the end of this line:
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.