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

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


1. Обзор

В этом кратком руководстве мы поговорим об ошибке компилятора Java

«ожидается класс, интерфейс или перечисление» .

В основном с этой ошибкой сталкиваются разработчики, которые являются новичками в мире Java.

Давайте рассмотрим несколько примеров этой ошибки и обсудим, как их исправить.


2. Неуместные фигурные скобки

Основной причиной ошибки

«ожидается класс, интерфейс или перечисление»

, как правило, является неуместная фигурная скобка


_ «}»

_

. Это может быть дополнительная фигурная скобка после урока. Это также может быть метод, случайно написанный вне класса.

Давайте посмотрим на пример:

public class MyClass {
    public static void main(String args[]) {
      System.out.println("Baeldung");
    }
}
}
----/MyClass.java:6: error: class, interface, or enum expected
}
^
1 error
----

В приведенном выше примере кода в последней строке есть дополнительная фигурная скобка __ «}», что приводит к ошибке компиляции. Если мы удалим его, код скомпилируется.

Давайте посмотрим на другой сценарий, где эта ошибка происходит:

public class MyClass {
    public static void main(String args[]) {
       //Implementation
    }
}
public static void printHello() {
    System.out.println("Hello");
}
----/MyClass.java:6: error: class, interface, or enum expected
public static void printHello()
^/MyClass.java:8: error: class, interface, or enum expected
}
^
2 errors
----

В приведенном выше примере мы получим ошибку, потому что метод

printHello ()

находится вне класса

MyClass

. Мы можем исправить это, переместив закрывающие фигурные скобки

«}»

в конец файла. Другими словами, переместите метод

printHello ()

внутрь

MyClass

.


3. Заключение

В этом кратком руководстве мы обсудили ошибку компилятора Java «ожидаемый класс, интерфейс или перечисление» и продемонстрировали две вероятные основные причины.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    In Java, the class interface or enum expected error is a compile-time error. There can be one of the following reasons we get “class, interface, or enum expected” error in Java: 

    Case 1: Extra curly Bracket

    Java

    class Hello {

        public static void main(String[] args)

        {

            System.out.println("Helloworld");

        }

    }

    }

    In this case, the error can be removed by simply removing the extra bracket.

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

        }

    }

    Case 3: Forgot to declare class at all

    There might be a chance that we forgot to declare class at all. We will get this error. Check if you have declared class, interface, or enum in your java file or not.

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

        }

    }

    Last Updated :
    28 Jan, 2021

    Like Article

    Save Article

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

    Case 1: Extra curly Bracket

    class Hello {

        public static void main(String[] args)

        {

            System.out.println("Helloworld");

        }

    }

    }

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

    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 и многому другому, см. Полный курс подготовки к собеседованию .


    1. Обзор

    В этом кратком руководстве мы поговорим об ошибке компилятора Java

    «ожидается класс, интерфейс или перечисление» .

    В основном с этой ошибкой сталкиваются разработчики, которые являются новичками в мире Java.

    Давайте рассмотрим несколько примеров этой ошибки и обсудим, как их исправить.


    2. Неуместные фигурные скобки

    Основной причиной ошибки

    «ожидается класс, интерфейс или перечисление»

    , как правило, является неуместная фигурная скобка


    _ «}»

    _

    . Это может быть дополнительная фигурная скобка после урока. Это также может быть метод, случайно написанный вне класса.

    Давайте посмотрим на пример:

    public class MyClass {
        public static void main(String args[]) {
          System.out.println("Baeldung");
        }
    }
    }
    ----/MyClass.java:6: error: class, interface, or enum expected
    }
    ^
    1 error
    ----

    В приведенном выше примере кода в последней строке есть дополнительная фигурная скобка __ «}», что приводит к ошибке компиляции. Если мы удалим его, код скомпилируется.

    Давайте посмотрим на другой сценарий, где эта ошибка происходит:

    public class MyClass {
        public static void main(String args[]) {
           //Implementation
        }
    }
    public static void printHello() {
        System.out.println("Hello");
    }
    ----/MyClass.java:6: error: class, interface, or enum expected
    public static void printHello()
    ^/MyClass.java:8: error: class, interface, or enum expected
    }
    ^
    2 errors
    ----

    В приведенном выше примере мы получим ошибку, потому что метод

    printHello ()

    находится вне класса

    MyClass

    . Мы можем исправить это, переместив закрывающие фигурные скобки

    «}»

    в конец файла. Другими словами, переместите метод

    printHello ()

    внутрь

    MyClass

    .


    3. Заключение

    В этом кратком руководстве мы обсудили ошибку компилятора Java «ожидаемый класс, интерфейс или перечисление» и продемонстрировали две вероятные основные причины.

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In Java, the class interface or enum expected error is a compile-time error. There can be one of the following reasons we get “class, interface, or enum expected” error in Java: 

    Case 1: Extra curly Bracket

    Java

    class Hello {

        public static void main(String[] args)

        {

            System.out.println("Helloworld");

        }

    }

    }

    In this case, the error can be removed by simply removing the extra bracket.

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

        }

    }

    Case 3: Forgot to declare class at all

    There might be a chance that we forgot to declare class at all. We will get this error. Check if you have declared class, interface, or enum in your java file or not.

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

        }

    }

    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

    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

    1. Обзор

    В этом кратком руководстве мы поговорим об ошибке компилятора Java «ожидаемый класс, интерфейс или перечисление». С этой ошибкой в ​​основном сталкиваются разработчики, которые плохо знакомы с миром Java.

    Давайте рассмотрим несколько примеров этой ошибки и обсудим, как их исправить.

    2. Неуместные фигурные скобки

    Основной причиной ошибки «ожидаемый класс, интерфейс или перечисление» обычно является неуместная фигурная скобка «}» . Это может быть дополнительная фигурная скобка после урока. Это также может быть метод, случайно написанный вне класса.

    Давайте посмотрим на пример:

    public class MyClass {
        public static void main(String args[]) {
          System.out.println("Baeldung");
        }
    }
    }
    /MyClass.java:6: error: class, interface, or enum expected } ^ 1 error

    В приведенном выше примере кода в последней строке есть дополнительная фигурная скобка «}», которая приводит к ошибке компиляции. Если мы его удалим, то код скомпилируется.

    Давайте посмотрим на другой сценарий, в котором возникает эта ошибка:

    public class MyClass {
        public static void main(String args[]) {
           //Implementation
        }
    }
    public static void printHello() {
        System.out.println("Hello");
    }
    /MyClass.java:6: error: class, interface, or enum expected public static void printHello() ^ /MyClass.java:8: error: class, interface, or enum expected } ^ 2 errors

    В приведенном выше примере мы получим ошибку, потому что метод printHello () находится за пределами класса MyClass . Мы можем исправить это, переместив закрывающие фигурные скобки «}» в конец файла. Другими словами, переместите метод printHello () внутрь MyClass .

    3. Заключение

    В этом кратком руководстве мы обсудили «ожидаемую ошибку класса, интерфейса или перечисления» компилятора Java и продемонстрировали две вероятные основные причины.


    Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

    If you have ever written Java programs using Notepad or inside DOS editor, then you know that how a single missing curly brace can blow your program and throw 100s of «illegal start of expression» errors during compilation of Java Programmer. I was one of those lucky people who started their programming on DOS editor, the blue window editor which allows you to write Java programs. I didn’t know about PATH, CLASSPATH, JDK, JVM, or JRE at that point. It’s our lab computer where everything is supposed to work as much as our instructor wants. 

    Since we don’t have the internet at that point in time, we either wait for the instructor to come and rescue us and we were surprised by how he solve the error by just putting one curly brace and all errors mysteriously go away.  

    Today, I am going to tell you about one such error,  «class, interface, or enum expected». This is another compile-time error in Java that arises due to curly braces. Typically this error occurs when there is an additional curly brace at the end of the program.

    Since everything is coded inside a class, interface, or enum in Java, once you close the curly brace for an existing class and add another closing curly braces, the compiler will expect another class is starting hence it will complain about class, interface, or enum keyword as shown in the following program:

    public class Main {
    
    public static void main(String[] args) {
       System.out.println("Helloworld");
      }
     }
    }

    If you compile this program using javac, you will get the following error:

    $ javac Main.java
    Main.java:14: class, interface, or enum expected
    }
    ^
    1 error

    Since this is a small program, you can easily spot the additional curly brace at the end of the problem but it’s very difficult in a big program with several classes and methods. 

    How to fix "class, interface, or enum expected" error in Java? Example

    This becomes even tougher if you are not using any IDE like Eclipse or NetBeans which will give you a visible sign of where an error is. If you know how to use Eclipse or any other Java IDE, just copy-paste your code into IDE and it will tell you the exact location of the error which hint to solve.

    Alternatively, if you are coding in Notepad, I assume you are a beginner, then try to correctly indent your code. n our example program above, notice that the two curly braces at the end of the program are at the same indentation level, which cannot happen in a valid program. Therefore, simply delete one of the curly braces for the code to compile, the error will go away as shown below:

    $ javac Main.java

    So, next time you get the «class, interface, or enum expected» error, just check if you additional curly braces a the end of your program.

    Other Java error troubleshooting experiences:

    • How to fix «variable might not have been initialized» error in Java? (solution)
    • Could not create the Java virtual machine Invalid maximum heap size: -Xmx (solution)
    • Error: could not open ‘C:Javajre8libamd64jvm.cfg’ (solution)
    • How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory (solution)
    • Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java (solution)
    • java.lang.OutOfMemoryError: Java heap space : Cause and Solution (steps)

    In this post, we will see how to fix «class interface or enum expected» error in java.

    There can be multiple reason for getting this error.

    Due to method outside class body

    This error you will generally get when you have accidentally put your method outside class body.
    Let’s see with the help of simple example.

    public class MyClass {

        public static void main(String args[]) {

        int count=0;

        }

    }

    public static void myMethod()

    {

            System.out.println(«My method»);

    }

    You will get below error when you run javac command.

    $javac MyClass.java
    MyClass.java:7: error: class, interface, or enum expected
    public static void myMethod()
    ^
    MyClass.java:10: error: class, interface, or enum expected
    }
    ^
    2 errors

    But if you use eclipse ide, you will get below error.

    Syntax error on token “}”, delete this token

    As you can see, eclipse provides you much better information regarding this error.
    I have given a very simple example, you might get this error in complex code. It is hard to identify issues with that so I will recommend you to use some ide like eclipse.

    Forgot to declare class at all

    This might sound silly but if you forgot to declare class at all, you will get this error.Please check if you have declated class, interface or enum in your java file or not.

    That’s all about class interface or enum expected error in java.I hope it will resolve this error for you.

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    1

    30.01.2021, 21:56. Показов 18524. Ответов 9


    ошибка java: class, interface, or enum expected

    Что за ошибка?

    где метод «third» надо указать, и как?

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

    0

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 22:02

    2

    Цитата
    Сообщение от Student Student
    Посмотреть сообщение

    Что за ошибка?

    Код нужно выкладывать текстом, а не скриншотом.
    По сабжу — методы в тело класса помести.

    1

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    30.01.2021, 22:10

     [ТС]

    3

    частично получилось, ругается на третий класс, почему-то
    Этот метод добавила

    так он вызвыается

    Код

    public static float third(float a, float b, float c, float d){
        return a*(b+(c/d));
        }

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

    0

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 22:12

    4

    Student Student, да ёмаё, код выложи ВЕСЬ!

    Добавлено через 10 секунд
    Прям как есть

    0

    Student Student

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    30.01.2021, 22:16

     [ТС]

    5

    Java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    
    package ru.**********.lesson1;
     
    public class FirstApp {
     
        // 1. Создать пустой проект в IntelliJ IDEA и прописать метод main()
        public static void main(String[] args){
        }
     
        // 2. Создать переменные всех пройденных типов данных и инициализировать их значения
            public static void second(){
                float val1 = 12.17f;
                char val2 = '*';
                long val3 = 1000L;
                String val4 = "Hello";
                int val5 = 10;
                boolean val6 = true;
            }
        }
     
        // 3. Написать метод вычисляющий выражение a * (b + (c / d)) и возвращающий результат, где a, b, c, d – аргументы этого метода, имеющие тип float
        public static float third(float a, float b, float c, float d){
        return a*(b+(c/d));
        }
     
        // 4. Написать метод, принимающий на вход два целых числа и проверяющий, что их сумма лежит в пределах от 10 до 20 (включительно), если да – вернуть true, в противном случае – false
        public static boolean fourth(int a, int b){
            return 10 <= a + b && a + b <= 20;
        }
       
     
     
        }

    0

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 22:20

    6

    Лучший ответ Сообщение было отмечено Student Student как решение

    Решение

    Student Student, я ж сказал — внеси методы в тело класса.
    Убери скобку с 18 строки

    1

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    30.01.2021, 22:36

     [ТС]

    7

    спасибо, а как в git передать?

    0

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 22:42

    8

    Никак. В git не передают!
    Ну а ежели имелось ввиду выложить на гитхаб или битбакет…

    0

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    30.01.2021, 23:33

     [ТС]

    9

    Подскажите, пожалуйста, почему в консоли не выводится никакого сообщения, а просто пишется, что ошибок нет?

    Код

    // 7. Написать метод, которому в качестве параметра передается строка, обозначающая имя. Метод должен вывести в консоль сообщение «Привет, указанное_имя!»
        public static void seventh(String name){
            System.out.println("Привет, %s!"+ name);

    0

    iSmokeJC

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 23:39

    10

    Потому что метод нужно вызвать

    Добавлено через 1 минуту
    Кстати, он у тебя написан неправильно

    Добавлено через 35 секунд

    Java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public class Cyber {
        public static void main(String[] args) {
            seventh("Student Student");
        }
     
        public static void seventh(String name) {
            System.out.printf("Привет, %s!", name);
        }
    }
    Bash
    1
    
    Привет, Student Student!

    0

    IT_Exp

    Эксперт

    87844 / 49110 / 22898

    Регистрация: 17.06.2006

    Сообщений: 92,604

    30.01.2021, 23:39

    Помогаю со студенческими работами здесь

    Error: Expected class, delegate, enum, interface, or struct
    Создал приложение winforms, добавил класс с реализацией методов, почему то куча ошибок типа…

    Ошибки в коде — Expected class, delegate, enum, interface, or struct
    С с# не знаком, полез на msdn.microsoft.com насчет ошибок, тоже не очень понятно. насчет cs1513…

    Ошибка main.cs(17,11): error CS1525: Unexpected symbol `void’, expecting `class’, `delegate’, `enum’, `interface’,
    Выскакивает ошибка main.cs(17,11): error CS1525: Unexpected symbol `void’, expecting `class’,…

    Ошибка «Runtime Error 430 class does not support Automation or expected Interface» под Win7
    Привет всем)

    Написанный мною скрипт, работает всего лишь на Windows 8, а на Windows 7 при…

    ‘class’ or ‘interface’ expected в имени метода
    Разрабатывая приложение на JavaFX, столкнулся с проблемой. Создал метод в контроллере, но при…

    Class does not support Automation or does not support expected interface
    в документе Ворд добавил
    Microsoft Forms 2.0 Frame стал на него вешать код, проверяю код, получаю…

    Искать еще темы с ответами

    Или воспользуйтесь поиском по форуму:

    10

    How to Fix Error: “Class, Interface, or Enum Expected” ?

    Learn via video course

    Java Course - Mastering the Fundamentals

    This becomes even tougher if you are not using any IDE like Eclipse or NetBeans which will give you a visible sign of where an error is. If you know how to use Eclipse or any other Java IDE, just copy-paste your code into IDE and it will tell you the exact location of the error which hint to solve.

    Alternatively, if you are coding in Notepad, I assume you are a beginner, then try to correctly indent your code. n our example program above, notice that the two curly braces at the end of the program are at the same indentation level, which cannot happen in a valid program. Therefore, simply delete one of the curly braces for the code to compile, the error will go away as shown below:

    $ javac Main.java

    So, next time you get the «class, interface, or enum expected» error, just check if you additional curly braces a the end of your program.

    Other Java error troubleshooting experiences:

    • How to fix «variable might not have been initialized» error in Java? (solution)
    • Could not create the Java virtual machine Invalid maximum heap size: -Xmx (solution)
    • Error: could not open ‘C:Javajre8libamd64jvm.cfg’ (solution)
    • How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory (solution)
    • Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java (solution)
    • java.lang.OutOfMemoryError: Java heap space : Cause and Solution (steps)

    In this post, we will see how to fix «class interface or enum expected» error in java.

    There can be multiple reason for getting this error.

    Due to method outside class body

    This error you will generally get when you have accidentally put your method outside class body.
    Let’s see with the help of simple example.

    public class MyClass {

        public static void main(String args[]) {

        int count=0;

        }

    }

    public static void myMethod()

    {

            System.out.println(«My method»);

    }

    You will get below error when you run javac command.

    $javac MyClass.java
    MyClass.java:7: error: class, interface, or enum expected
    public static void myMethod()
    ^
    MyClass.java:10: error: class, interface, or enum expected
    }
    ^
    2 errors

    But if you use eclipse ide, you will get below error.

    Syntax error on token “}”, delete this token

    As you can see, eclipse provides you much better information regarding this error.
    I have given a very simple example, you might get this error in complex code. It is hard to identify issues with that so I will recommend you to use some ide like eclipse.

    Forgot to declare class at all

    This might sound silly but if you forgot to declare class at all, you will get this error.Please check if you have declated class, interface or enum in your java file or not.

    That’s all about class interface or enum expected error in java.I hope it will resolve this error for you.

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    1

    30.01.2021, 21:56. Показов 18524. Ответов 9


    ошибка java: class, interface, or enum expected

    Что за ошибка?

    где метод «third» надо указать, и как?

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

    0

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 22:02

    2

    Цитата
    Сообщение от Student Student
    Посмотреть сообщение

    Что за ошибка?

    Код нужно выкладывать текстом, а не скриншотом.
    По сабжу — методы в тело класса помести.

    1

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    30.01.2021, 22:10

     [ТС]

    3

    частично получилось, ругается на третий класс, почему-то
    Этот метод добавила

    так он вызвыается

    Код

    public static float third(float a, float b, float c, float d){
        return a*(b+(c/d));
        }

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

    0

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 22:12

    4

    Student Student, да ёмаё, код выложи ВЕСЬ!

    Добавлено через 10 секунд
    Прям как есть

    0

    Student Student

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    30.01.2021, 22:16

     [ТС]

    5

    Java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    
    package ru.**********.lesson1;
     
    public class FirstApp {
     
        // 1. Создать пустой проект в IntelliJ IDEA и прописать метод main()
        public static void main(String[] args){
        }
     
        // 2. Создать переменные всех пройденных типов данных и инициализировать их значения
            public static void second(){
                float val1 = 12.17f;
                char val2 = '*';
                long val3 = 1000L;
                String val4 = "Hello";
                int val5 = 10;
                boolean val6 = true;
            }
        }
     
        // 3. Написать метод вычисляющий выражение a * (b + (c / d)) и возвращающий результат, где a, b, c, d – аргументы этого метода, имеющие тип float
        public static float third(float a, float b, float c, float d){
        return a*(b+(c/d));
        }
     
        // 4. Написать метод, принимающий на вход два целых числа и проверяющий, что их сумма лежит в пределах от 10 до 20 (включительно), если да – вернуть true, в противном случае – false
        public static boolean fourth(int a, int b){
            return 10 <= a + b && a + b <= 20;
        }
       
     
     
        }

    0

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 22:20

    6

    Лучший ответ Сообщение было отмечено Student Student как решение

    Решение

    Student Student, я ж сказал — внеси методы в тело класса.
    Убери скобку с 18 строки

    1

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    30.01.2021, 22:36

     [ТС]

    7

    спасибо, а как в git передать?

    0

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 22:42

    8

    Никак. В git не передают!
    Ну а ежели имелось ввиду выложить на гитхаб или битбакет…

    0

    0 / 0 / 0

    Регистрация: 19.09.2019

    Сообщений: 50

    30.01.2021, 23:33

     [ТС]

    9

    Подскажите, пожалуйста, почему в консоли не выводится никакого сообщения, а просто пишется, что ошибок нет?

    Код

    // 7. Написать метод, которому в качестве параметра передается строка, обозначающая имя. Метод должен вывести в консоль сообщение «Привет, указанное_имя!»
        public static void seventh(String name){
            System.out.println("Привет, %s!"+ name);

    0

    iSmokeJC

    Йуный падаван

    Эксперт PythonЭксперт Java

    13854 / 8096 / 2470

    Регистрация: 21.10.2017

    Сообщений: 19,568

    30.01.2021, 23:39

    10

    Потому что метод нужно вызвать

    Добавлено через 1 минуту
    Кстати, он у тебя написан неправильно

    Добавлено через 35 секунд

    Java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public class Cyber {
        public static void main(String[] args) {
            seventh("Student Student");
        }
     
        public static void seventh(String name) {
            System.out.printf("Привет, %s!", name);
        }
    }
    Bash
    1
    
    Привет, Student Student!

    0

    IT_Exp

    Эксперт

    87844 / 49110 / 22898

    Регистрация: 17.06.2006

    Сообщений: 92,604

    30.01.2021, 23:39

    Помогаю со студенческими работами здесь

    Error: Expected class, delegate, enum, interface, or struct
    Создал приложение winforms, добавил класс с реализацией методов, почему то куча ошибок типа…

    Ошибки в коде — Expected class, delegate, enum, interface, or struct
    С с# не знаком, полез на msdn.microsoft.com насчет ошибок, тоже не очень понятно. насчет cs1513…

    Ошибка main.cs(17,11): error CS1525: Unexpected symbol `void’, expecting `class’, `delegate’, `enum’, `interface’,
    Выскакивает ошибка main.cs(17,11): error CS1525: Unexpected symbol `void’, expecting `class’,…

    Ошибка «Runtime Error 430 class does not support Automation or expected Interface» под Win7
    Привет всем)

    Написанный мною скрипт, работает всего лишь на Windows 8, а на Windows 7 при…

    ‘class’ or ‘interface’ expected в имени метода
    Разрабатывая приложение на JavaFX, столкнулся с проблемой. Создал метод в контроллере, но при…

    Class does not support Automation or does not support expected interface
    в документе Ворд добавил
    Microsoft Forms 2.0 Frame стал на него вешать код, проверяю код, получаю…

    Искать еще темы с ответами

    Или воспользуйтесь поиском по форуму:

    10

    How to Fix Error: “Class, Interface, or Enum Expected” ?

    Learn via video course

    Java Course - Mastering the Fundamentals

    Java Course — Mastering the Fundamentals

    Tarun Luthra

    Free

    5

    icon_usercirclecheck-01

    Enrolled: 52190

    Start Learning

    The braces in java are served as a scope limit. The beginning and end of a code block are indicated by curly brackets.

    Curly brackets cause the compile-time error known as the class interface or enum expected error in Java. This issue typically happens when the program ends with an extra curly brace.

    Since everything in Java is programmed inside a class, interface, or enum, if you close the curly bracket for one class and add another, the compiler will assume that another class is starting and will complain about the class, interface, or enum keyword, as illustrated in the following program:

    
    

    Code explanation
    If we compile this code it will raise this error

    
    

    because of extra braces.

    Misplaced Curly Braces

    The root cause of the “class, interface, or enum expected” error is typically a misplaced curly brace “}”. This can be an extra curly brace after the class. It could also be a method accidentally written outside the class.

    
    

    Code Explanation
    The following error will be raised

    
    

    To solve this error simply remove extra brace

    
    

    Function Outside Class (Intro+ Add Code Example Ti Fix Error)

    A method present outside of a class may also be the cause of this problem. The compilation process will fail since this method does not belong to any class. Moving the method within the class will fix this issue.

    
    

    Code Explanation
    In Above code method1 is outside of class classb this will raise error.To solve this placed method1 inside of classb.

    
    

    Multiple Package

    In a Java file, only one package can be declared. The expected compilation error for a class, interface, or enum will occur if we have more packages than necessary.

    
    

    Code Explanation
    To solve error import only one package.Each source file can only have one package statement, and it must apply to all of the file’s types.

    
    

    Conclusion

    • The class, interface, or enum expected error occurs due to a few different reasons.
    • This error can occur due to misplaced braces by removing extra braces or adding missing braces this error can be solved.
    • If a method is included outside of a class, then this error can happen. By placing method within class error can be solved.
    • This error can be raised if multiple packages are imported in a java file. It is possible to fix errors by importing just one package.
    • The solution to this problem is rather simple.

    Понравилась статья? Поделить с друзьями:
  • Ошибка jam4211 на мфу kyocera
  • Ошибка kb3033929 при установке программы
  • Ошибка jam4211 замята бумага в задней крышке
  • Ошибка just in time debugging что это
  • Ошибка j4220 kyocera fs 1125mfp