Ошибка java class interface or enum expected

The class, interface, or enum expected error is the most common runtime error in Java. Find out its main causes and how you can easily resolve them in your code.

Introduction

Java errors are the lifelong enemy of every developer, be it a novice or an expert. A Java developer faces a plethora of different types of errors. One such error is the class interface or enum expected error.

In this article, we will be focusing on the reason behind the occurrences of this error and how to resolve it.

The class interface or enum expected error is a compile-time error in Java. It is mainly faced by the developers at their early stages in Java development.

The primary reason behind the class interface or enum expected error is the incorrect number of curly braces. Typically, this error is faced when there is an excess or shortage of a curly brace at the end of the code.

new java job roles

Since the whole code is placed inside a class, interface, or enum in Java, an extra curly brace makes the compiler understand that another class is starting and no closing braces after that is considered as the incompletion of class hence it will complain about class, interface, or enum keyword.

We will be now discussing some of the basic causes of class, interface, or enum expected error and how you can fix them.

1. Misplaced Curly Braces

The primary cause of the “class, interface or enum expected” error is typically a mistyped curly brace “}” in your code.

This error could have been encountered due to either an extra curly brace after the class or due to a missed curly brace in your code.

Look at this example below:

1.   public class MyClass {
2.	public static void main(String args[]) {
3.	  System.out.println("Hello World");
4.      }
5.   }
6.   }

Error:

/MyClass.java:6: error: class, interface, or enum expected
}
^
1 error

In the above code demonstration, there is an extra “}” curly brace at the last which is resulting in the compilation error. The removal of the extra “}” can easily resolve the error in this case.

2. A Function is declared outside of the class

Let’s look at another scenario where this error usually occurs:

1.  public class MyClass {
2.     public static void main(String args[]) {
3.	   //Implementation
4.     }
5.  }
6.  public static void printMessage() {
7.	System.out.println("Hello World");
8.  }
Error:

/MyClass.java:6: error: class, interface, or enum expected
public static void printHello()
^
/MyClass.java:8: error: class, interface, or enum expected
}
^
2 errors

In the above example, the class, interface, or enum expected error is faced because the function printHello()  is defined outside of the class.

Although, this error is also somewhat due to misplacing of curly braces but it is important to identify this different cause so that the user would also quickly look at all the methods and their placement in the code to make sure that all functions are properly placed.

This can be easily fixed by just moving the closing curly braces “}” to the end of the class so that the printHello() method will be now inside the MyClass.

3. Class is not declared

You would also face this error if you have not declared the class. There might be a chance that you forgot to declare the class at all.

Always make sure that the class, interface, or enum is properly declared in your java file.

4. Declaration of multiple packages in the same file

More than one package cannot be present in the same Java source file. It will result in the class interface or enum expected error if your source file contains more than one package.

See the code example below where two packages are present in the same code. You must avoid this in your code:

1.  package p1;
2.  class class1 {
3.	void fun1() { System.out.println("Hello World"); }
4.  }
5.  package p2; //getting class interface or enum expected
6.  public class class2 {
7.	public static void main(String[] args)
8.      {
9.	    System.out.println("Hello World");
10.	}

Tips to prevent the “class, interface, or enum expected” error in Java

All the codes that we have discussed above consisted of very limited lines which makes it very easy for users to spot the misplaced curly brace but it will not be that simple if we have to look for it in a huge code with multiple methods and classes.

·Use a modern IDE

The use of an IDE can be a very good solution for preventing this error.

Various new and modern IDEs have features that automatically add the missing curly braces as detected or they right away highlights the extra added braces in your code before compilation.

Despite that, even if the error occurs, modern IDEs like Eclipse or Netbeans also give the user a visible sign of where the error is located and it will pinpoint the exact location of the error in your code.

·Indent your code

Assuming that you are not able to use an IDE,  if you are writing your code in a word processing software such as Notepad, then try to correctly indent your code.

The clear indentations make it easier to identify if there are extra curly braces at the end of the code as they would be at the same indentation level, which should not be part of a valid code.

You can simply remove the extra curly braces for the code before compiling it and the class interface or enum expected error can be easily prevented.

Wrapping it up

We discussed various reasons behind the occurrence of class, interface, or enum expected error. We also looked into the same ways to prevent this error.

It is a very trivial error and can be very quickly solved but it can sometimes become a bit troubling especially when occurred in a big code. To cater to that, always use a modern IDE to prevent this error.

See Also: How To Iterate Over a Map In Java

new Java jobs

I have been troubleshooting this program for hours, trying several configurations, and have had no luck. It has been written in java, and has 33 errors (lowered from 50 before)

Source Code:

/*This program is named derivativeQuiz.java, stored on a network drive I have permission to edit
The actual code starts below this line (with the first import statement) */
import java.util.Random;
import java.Math.*;
import javax.swing.JOptionPane;
public static void derivativeQuiz(String args[])
{
    // a bunch of code
}

The error log (compiled in JCreator):

--------------------Configuration: <Default>--------------------
H:Derivative quizderivativeQuiz.java:4: class, interface, or enum expected
public static void derivativeQuiz(String args[])
              ^
H:Derivative quizderivativeQuiz.java:9: class, interface, or enum expected
    int maxCoef = 15;
    ^
H:Derivative quizderivativeQuiz.java:10: class, interface, or enum expected
    int question = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter the number of questions you wish to test on: "));
    ^
H:Derivative quizderivativeQuiz.java:11: class, interface, or enum expected
    int numExp = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter the maximum exponent allowed (up to 5 supported):" ));
    ^
H:Derivative quizderivativeQuiz.java:12: class, interface, or enum expected
    Random random = new Random();
    ^
H:Derivative quizderivativeQuiz.java:13: class, interface, or enum expected
    int coeff;
    ^
H:Derivative quizderivativeQuiz.java:14: class, interface, or enum expected
    String equation = "";
    ^
H:Derivative quizderivativeQuiz.java:15: class, interface, or enum expected
    String deriv = "";
    ^
H:Derivative quizderivativeQuiz.java:16: class, interface, or enum expected
    for(int z = 0; z <= question; z++)
    ^
H:Derivative quizderivativeQuiz.java:16: class, interface, or enum expected
    for(int z = 0; z <= question; z++)
                   ^
H:Derivative quizderivativeQuiz.java:16: class, interface, or enum expected
    for(int z = 0; z <= question; z++)
                                  ^
H:Derivative quizderivativeQuiz.java:19: class, interface, or enum expected
        deriv = "";
        ^
H:Derivative quizderivativeQuiz.java:20: class, interface, or enum expected
        if(numExp >= 5)
        ^
H:Derivative quizderivativeQuiz.java:23: class, interface, or enum expected
            equation = coeff + "X^5 + ";
            ^
H:Derivative quizderivativeQuiz.java:24: class, interface, or enum expected
            deriv = coeff*5 + "X^4 + ";
            ^
H:Derivative quizderivativeQuiz.java:25: class, interface, or enum expected
        }
        ^
H:Derivative quizderivativeQuiz.java:29: class, interface, or enum expected
            equation = equation + coeff + "X^4 + ";
            ^
H:Derivative quizderivativeQuiz.java:30: class, interface, or enum expected
            deriv = deriv + coeff*4 + "X^3 + ";
            ^
H:Derivative quizderivativeQuiz.java:31: class, interface, or enum expected
        }
        ^
H:Derivative quizderivativeQuiz.java:35: class, interface, or enum expected
            equation = equation + coeff + "X^3 + ";
            ^
H:Derivative quizderivativeQuiz.java:36: class, interface, or enum expected
            deriv = deriv + coeff*3 + "X^2 + ";
            ^
H:Derivative quizderivativeQuiz.java:37: class, interface, or enum expected
        }
        ^
H:Derivative quizderivativeQuiz.java:41: class, interface, or enum expected
            equation = equation + coeff + "X^2 + ";
            ^
H:Derivative quizderivativeQuiz.java:42: class, interface, or enum expected
            deriv = deriv + coeff*2 + "X + ";
            ^
H:Derivative quizderivativeQuiz.java:43: class, interface, or enum expected
        }
        ^
H:Derivative quizderivativeQuiz.java:47: class, interface, or enum expected
            equation = equation + coeff + "X + ";
            ^
H:Derivative quizderivativeQuiz.java:48: class, interface, or enum expected
            deriv = deriv + coeff;
            ^
H:Derivative quizderivativeQuiz.java:49: class, interface, or enum expected
        }
        ^
H:Derivative quizderivativeQuiz.java:53: class, interface, or enum expected
            equation = equation + coeff;
            ^
H:Derivative quizderivativeQuiz.java:54: class, interface, or enum expected

            if(deriv == "")
            ^
H:Derivative quizderivativeQuiz.java:57: class, interface, or enum expected
            }
            ^
H:Derivative quizderivativeQuiz.java:114: class, interface, or enum expected
    JOptionPane.showMessageDialog(null, "Question " + z + "\" + question + "nDerivative: " + deriv);
    ^
H:Derivative quizderivativeQuiz.java:115: class, interface, or enum expected
    }
    ^
33 errors

Process completed.

I feel like this is a basic error, and yet I can’t seem to find it.
If it makes a difference, I am using JCreator to compile and everything is installed correctly.

UPDATE:
I have fixed the errors involved (Class declaration and incorrect import statements (someone went back and deleted a few semicolons))

Working code:

import java.util.Random;
import javax.swing.JOptionPane;
import java.lang.String;
public class derivativeQuiz_source{
public static void main(String args[])
{
    //a bunch more code
}
}

Thanks for all the help

В Java ожидаемая ошибка интерфейса класса или перечисления является ошибкой времени компиляции. Может быть одна из следующих причин, по которым мы получаем ошибку «ожидаемый класс, интерфейс или перечисление» в Java:

Case 1: Extra curly Bracket

class Hello {

    public static void main(String[] args)

    {

        System.out.println("Helloworld");

    }

}

}

В этом случае ошибку можно устранить, просто сняв лишнюю скобу.

Java

class Hello {

    public static void main(String[] args)

    {

        System.out.println("Helloworld");

    }

}

Case 2: Function outside the class

Java

class Hello {

    public static void main(String args[])

    {

        System.out.println("HI");

    }

}

public static void func() { System.out.println("Hello"); }

In the earlier example, we get an error because the method func() is outside the Hello class. It can be removed by moving the closing curly braces “}” to the end of the file. In other words, move the func() method inside of​ Hello.

Java

class Hello {

    public static void main(String args[])

    {

        System.out.println("HI");

    }

    public static void func()

    {

        System.out.println("Hello");

    }

}

Случай 3: Забыл объявить класс вообще

Возможно, мы вообще забыли объявить класс. Мы получим эту ошибку. Проверьте, объявили ли вы класс, интерфейс или перечисление в своем java-файле или нет.

Case 4: Declaring more than one package in the same file

Java

package A;

class A {

    void fun1() { System.out.println("Hello"); }

}

package B;

public class B {

    public static void main(String[] args)

    {

        System.out.println("HI");

    }

}

We can not put different packages into the same source file. In the source file, the package statement should be the first line. 

Java

package A;

class A {

    void fun1() { System.out.println("Hello"); }

}

public class B {

    public static void main(String[] args)

    {

        System.out.println("HI");

    }

}

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса «Основы Java и Java Collections» по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

РЕКОМЕНДУЕМЫЕ СТАТЬИ

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка java address already in use bind
  • Ошибка jam0501 kyocera m2040dn
  • Ошибка jam0000 принтер kyocera
  • Ошибка j4020 kyocera 1025
  • Ошибка j338 пассат б5

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

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