Меню

Else without if ошибка java

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

Óscar López's user avatar

Óscar López

230k37 gold badges309 silver badges383 bronze badges

asked Oct 25, 2012 at 0:07

user1740066's user avatar

3

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.

answered Oct 25, 2012 at 0:09

Óscar López's user avatar

Óscar LópezÓscar López

230k37 gold badges309 silver badges383 bronze badges

0

The issue is that the first if if (temp > 95 || temp < 20); is the same using normal indentation as

if (temp > 95 || temp < 20)
{
}

That 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

if (temp > 95 || temp  < 20)  
{
  System.out.println ("Visit our shops");
} else if (temp >= 80)
{
    System.out.println ("Swimming");
} else if (temp >=60)
{ 
   System.out.println ("Tennis");
} else if (temp >= 40)
{
     System.out.println ("Golf");
} else if (temp >= 20)
{
   System.out.println ("Skiing");                                                                                                                                                                                                                                                                   
}

answered Oct 25, 2012 at 0:13

mmmmmm's user avatar

mmmmmmmmmmmm

32k27 gold badges88 silver badges115 bronze badges

I am going to reformat this for you. If you use curly brackets, you will never have this problem.

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) //<-- I removed the semicolon that caused the error
        {
            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");
                        }
                    }
                }
            }
        }
    }
}

answered Oct 25, 2012 at 1:28

byteherder's user avatar

byteherderbyteherder

3312 silver badges9 bronze badges

else without if error is mostly faced by the java beginners. As the name suggests java compiler is unable to find an if statement associated with your else statement. else statements do not execute unless they are associated with the if statement. As always, first, we will produce the error before moving on to the solution.

Read Also: [Fixed] Variable might not have been initialized

[Fixed] error: ‘else’ without ‘if’

Example 1: Producing the error by ending if statement with a semi-colon

public class ElseWithoutIf {
    public static void main(String args[]) {
        int input = 79;        

if(input > 100);

{
          System.out.println("input is greater than 100");
        }
        else 
        {
          System.out.println("input is less than or equal to 100");
        }
    }
}

Output:
/ElseWithoutIf.java:8: error: ‘else’ without ‘if’
   else {
   ^
1 error

Explanation:

The statement if(input > 100); is equivalent to writing

if (input > 100)

{
}

i.e. input is greater than 100 then execute an empty block. There is no else block for this. As a result, the next line else block does not have a corresponding if block, thus, produces the error: else without if.

Solution:

The above compilation error can be resolved by removing the semicolon.

public class ElseWithoutIf {
    public static void main(String args[]) {
        int input = 79;        

if(input > 100)

{ System.out.println("input is greater than 100"); } else
        {
          System.out.println("input is less than or equal to 100");
        }
    }
}

Output:
input is less than or equal to 100

Example 2: Producing the error by missing the closing bracket in if condition

Just like the above example, we will produce the error first before moving on to the solution.

public class ElseWithoutIf2 {
    public static void main(String args[]) {
        int input = 89;        
        if(input > 100) 
        { 
          System.out.println("inside if");                else 
        {
            System.out.println("inside else");
        }
    }
}

Output:
/ElseWithoutIf2.java:8: error: ‘else’ without ‘if’
   else

   ^

Explanation:

In the above example, if condition closing bracket is missing, hence, we are getting the else without if error.

Solution:

The above compilation error can be resolved by inserting the missing closing bracket as shown below.

public class ElseWithoutIf2 {
    public static void main(String args[]) {
        int input = 89;        
        if(input > 100) 
        { 
          System.out.println("inside if");       

}

else { System.out.println("inside else"); } } }

Output:
inside else

Example 3: Producing the error by having more than one else clause for an if statement

public class ElseWithoutIf3 {
    public static void main(String args[]) {
        int input = 99;        
        if(input > 100)
        {
          System.out.println("input is greater than 100");
        }        

else

{ System.out.println("input is less than 100"); } else { System.out.println("100"); } } }

Output:
/ElseWithoutIf3.java:12: error: ‘else’ without ‘if’
   else

   ^
1 error

Explanation:

In the above scenario, you are chaining the two elses together that is not correct syntax, hence, resulting in the error. The correct syntax is given below:

if(condition) 
{
   //do A;
}
else if(condition)
{
   //do B;
}
else
{
   //do C;
}

Solution:

The above compilation error can be resolved by providing correct if-elseif-else syntax as shown below.

public class ElseWithoutIf3 {
    public static void main(String args[]) {
        int input = 99;        
        if(input > 100)
        {
          System.out.println("input is greater than 100");
        }        

else if (input < 100)

{ System.out.println("input is less than 100"); } else { System.out.println("100"); } } }

Output:
input is less than 100

The best way to deal with error: ‘else’ without ‘if’ is always to use curly braces to show what is executed after if. Learn to indent the code too as it helps in reading and understanding.

  1. the error: 'else' without 'if' in Java
  2. Reasons for error: 'else' without 'if' in Java
  3. Fix the error: 'else' without 'if' in Java

Fix the Error: Else Without if in Java

Today, we will learn about an error saying 'else' without 'if' while writing code in Java. We will also figure out the possible reasons causing this error and find its solution.

the error: 'else' without 'if' in Java

Usually, this kind of error is faced by newbies in Java programming. Before moving toward the causes and solution for this error, let’s write a program that produces this error and understand it.

So, assuming that we are Python experts and beginners in Java. So, we will write the Java program containing if-else as follows.

Example Code:

//import libraries
import java.util.Scanner;

//decide future activity based on the current temperature
public class Test{
    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 ("Sking");                                      }//end main()
}//end Test Class

Error:

fix else without if an error in java - error

In this program, we get the current temperature from the user and decide our future activity based on the current temperature. The image above shows that we are getting a logical error about which NetBeans IDE informs at compile time.

So, we cannot even execute the code until we resolve the error. For that, we will have to know the possible reasons below.

Reasons for error: 'else' without 'if' in Java

The error itself is explanatory, which says that a Java compiler cannot find an if statement associated with the else statement. Remember that the else statement does not execute unless they’re associated with an if statement.

So, the possible reasons are listed below.

  1. The first reason is that we forgot to write the if block before the else block.
  2. The closing bracket of the if condition is missing.
  3. We end the if statement by using a semi-colon.

How to solve this error? Let’s have a look at the following section.

Fix the error: 'else' without 'if' in Java

Example Code:

//import libraries
import java.util.Scanner;

public class Test {
    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");
        }//end if
        else if (temp <= 95) {
            if (temp >= 80) {
                System.out.println("Swimming");
            } //end if
            else if (temp >= 60) {
                if (temp <= 80) {
                    System.out.println("Tennis");
                }//end if
                else if (temp >= 40) {
                    if (temp < 60) {
                        System.out.println("Golf");
                    }//end if
                    else if (temp < 40) {
                        if (temp >= 20) {
                            System.out.println("Sking");
                        }//end if
                    }//end else-if
                }//end else-if
            }//end else-if
        }//end else-if
    }//end main()
}//end Test Class

Output:

What's the current temperature?
96
Visit our shops

We removed the semi-colon (;) from the end of the if statement and placed the {} for each block to fix an error saying 'else' without 'if'.

It is better to use curly brackets {} until we are expert enough and know where we can omit them (we can omit them when we have a single statement in the block).

Вопрос:

Получение инструкции else без if:

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 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");
}
}

Мне нужно использовать каскадирование, если это почему-то похоже. Кроме того, не могли бы вы сообщить мне, если бы я сделал каскадный, если правильно? Я не смог найти хороший пример каскадирования, если так я просто сделал все возможное, зная, что такое каскадирование.

LazyDaysCamp.java:14: error: 'else' without 'if'
else if (temp <= 95)
^
1 error

Что ошибка, которую я получаю

Лучший ответ:

Удалите точку с запятой в конце этой строки:

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

И, пожалуйста, используйте фигурные скобки! Java не похожа на Python, где отступы кода создают новую область блока. Лучше играть в нее безопасно и всегда использовать фигурные скобки – по крайней мере, пока вы не получите больше опыта с языком и не поймете, когда сможете их опустить.

Ответ №1

Проблема в том, что первая, если if (temp > 95 || temp < 20); совпадает с обычным отступом как

if (temp > 95 || temp < 20)
{
}

То есть, если temp не находится между 20 и 95, тогда выполните пустой блок. Для этого нет другого.

В следующей строке else нет, если это соответствует ему, и, таким образом, выдает вашу ошибку

Лучший способ справиться с этим – всегда использовать фигурные скобки, чтобы показать, что выполняется после if. Это не означает, что компилятор ловит ошибки, но сначала вы, скорее всего, увидите какие-либо проблемы, увидев отступ, а также ошибки могут показаться более читаемыми. Однако вы можете использовать такие инструменты, как eclipse, checkstyle или FindBugs, которые расскажут вам, если вы не использовали {} или использовали пустой блок.

Лучший способ может быть, сортировка логики при повторном тестировании

if (temp > 95 || temp  < 20)
{
System.out.println ("Visit our shops");
} else if (temp >= 80)
{
System.out.println ("Swimming");
} else if (temp >=60)
{
System.out.println ("Tennis");
} else if (temp >= 40)
{
System.out.println ("Golf");
} else if (temp >= 20)
{
System.out.println ("Skiing");
}

Ответ №2

Я собираюсь переформатировать это для вас. Если вы используете фигурные скобки, у вас никогда не будет этой проблемы.

public class LazyDaysCamp
{
public static void main (String[] args)
{
int temp;
Scanner scan = new Scanner(System.in);

System.out.println ("What the current temperature?");
temp = scan.nextInt();
if (temp > 95 || temp < 20) //<-- I removed the semicolon that caused the error
{
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");
}
}
}
}
}
}
}

Ответ №3

Эта ошибка возникает из-за того, что вы ввели точку с запятой после оператора if.
Удалите точку с запятой в конце первого оператора if в строке 12.

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


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Hello friends, i’m Muhamet from Kosovo and i’m the new member here..

I have a problem, can anyone help me? Thanks.  

Here is the code:

ERROR : else without if ?


posted 5 years ago


  • Likes 1
  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Welcome to the Ranch!

Take a very close look at line 13.

Examine it character by character.

By the way, don’t use == to compare Strings. Use equals() instead. Or maybe equalsIgnoreCase() because you ask for Yes but test for yes.

Muhamet Ternava

Greenhorn

Posts: 2


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Muhamet Ternava wrote:Hello friends, i’m Muhamet from Kosovo and i’m the new member here..

I have a problem, can anyone help me? Thanks.  

Here is the code:

ERROR : else without if ?

NOW IT’S OKAY — THANKS !!

Marshal

Posts: 77152


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Muhamet Ternava wrote:. . . NOW IT’S OKAY — THANKS !!

No, it still looks incorrect. Just because code compiles, that doesn’t mean it is correct. There were two errors, one which will stop the code compiling, and another which will cause the code to run incorrectly. Even though you have removed the ; from line 13, you might still have the other error.

As on all websites, please don’t write ALL UPPER CASE.

And welcome to the Ranch


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

line 13 needs to be «Yes» and not «yes» because your program is asking for an input of Yes or No.


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

As others have said, using «if (answer.equals(«Yes»))» would be a much better alternative to line 13. However, to answer your specific error of having an else without an if statement, that would be because you do not have the else statement before the closing brackets of the if statement, thus making it not a part of the statement.


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

cris ortiz wrote:line 13 needs to be «Yes» and not «yes» because your program is asking for an input of Yes or No.

No, the capitalization has nothing to do with the issue. See the other replies regarding the use of == vs.

equals()

when comparing String values.


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Makayla Roberts wrote:However, to answer your specific error of having an else without an if statement, that would be because you do not have the else statement before the closing brackets of the if statement, thus making it not a part of the statement.

That is not correct. Read the very first reply in this thread by

Bartender

Saloon Keeper Pawel Baczyński — that hints at the actual reason for the «else without if» error message.


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator


Why doesn’t the OP’s compiler say anything about the error?

Mine does because I used the -Xlint option

Campbell Ritchie

Marshal

Posts: 77152


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Maybe OP isn’t familiar with -Xlint.


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

because of the use of == on a string, it won’t work and you should rather use .equals() for string values.

to help with the answer having uppercase letters you can add .toLower() to the end of the assigning of answer to make the string value all lower case letters, that way you don’t have to worry about the user inputting uppercase or lower case values when comparing strings.


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Take the semicolon out of line 13


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

The if statement is whats causing the issues. The semicolon after the if (answer == «yes»); is what’s messing it up.

This is one way it should look.

 


posted 5 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

On line 13, you use ‘==’ to compare strings, which doesn’t work.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Elsawin нелицензированная версия ошибка
  • Elsawin error 80004005 неопознанная ошибка source unknown description not available ок