Java else without if ошибка

Выдает ошибку error: ‘else’ without ‘if’, хотя else в If. Не могу разобраться.

package com.javarush.task.pro.task04.task0408;

import java.util.Scanner;

/*
Максимум из введенных чисел
*/

public class Solution {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int max = 0;

while (console.hasNextInt())
{
int x = console.nextInt();
if (x > max){
if ((x % 2) != 0){
continue;
}
max = x;
else {
System.out.print(max = Integer.MIN_VALUE);
}
}
}
System.out.println(max);
}
}

Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

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

232k37 gold badges310 silver badges386 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

232k37 gold badges310 silver badges386 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

32.1k27 gold badges87 silver badges116 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);

Понравилась статья? Поделить с друзьями:
  • Java 404 ошибка
  • Jasper ошибка 0022
  • Jane is an painter исправьте ошибки
  • Jane is a bit kind исправить ошибку
  • Jaguar x type ошибка p1647