Class or interface expected java что делать
Перейти к содержимому

Class or interface expected java что делать

  • автор:

Ошибка в коде «java: class, interface, or enum expected» В чем проблема?

Не компилируется код, не понимаю в чем проблема, подскажите пожалуйста.

package com.andrei; import java.io.*; public class Parts < String name; int age; double price; int date; public Parts(String name)< this.name = name; >public void empAge(int empAge) < age = empAge; >public void empPrice(double empPrice) < price = empPrice; >public void empDate(int empDate) < date = empDate; >public void printParts() < System.out.println("Назва запчастини:"+ name ); System.out.println("Кількість:" + age ); System.out.println("Ціна:" + price ); System.out.println("Термін зберігання:" + date); >> import java.io.*; public class PartsTest < public static void main(String args[])< Parts empOne = new Parts("Диски"); Parts empTwo = new Parts("Лобовое стекло"); empOne.empAge(11); empOne.empPrice(11500.53); empOne.empDate(48); empOne.printParts(); empTwo.empAge(3); empTwo.empPrice(15000.35); empTwo.empDate(72); empTwo.printParts(); >>
  • Вопрос задан более двух лет назад
  • 561 просмотр

11 комментариев

Простой 11 комментариев

Ошибка «class, interface, or enum expected»

Задача на языке JAVA: создать одномерный массив, заполнить его по формуле arr[i] = Math.pow(i, i) Мое решение:

public class Main < public static void main(String[] args) < int [] arr = ; for (int i = 0; i < arr.length; i++)< arr[i] = Math.pow(i, i); System.out.println(arr[i]); >> > 

Не пойму почему выводит ошибку:Error:(35, 1) java: class, interface, or enum expected — понимаю что я не указал класс (скорее всего double). Прошу по возможности развернуто объяснить что не так, и почему, в чем ошибка.

Отслеживать

26.2k 7 7 золотых знаков 31 31 серебряный знак 48 48 бронзовых знаков

задан 16 авг 2021 в 21:47

31 1 1 серебряный знак 8 8 бронзовых знаков

Ошибка компилятора Java: «ожидается класс, интерфейс или перечисление»

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

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

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

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

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

 public class MyClass    public static void main(String args[])    System.out.println("ForEach");   >   >   > 
/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 «ожидается класс, интерфейс или перечисление» и продемонстрировали две вероятные основные причины.

Java Compiler Error: “class, interface, or enum expected”

A quick guide to materially improve your tests with Junit 5:

Partner – Payara – NPI EA (cat=JAVA EE)

announcement - icon

Accelerate Your Jakarta EE Development with Payara Server!

With best-in-class guides and documentation, Payara essentially simplifies deployment to diverse infrastructures.

Beyond that, it provides intelligent insights and actions to optimize Jakarta EE applications.

The goal is to apply an opinionated approach to get to what’s essential for mission-critical applications — really solid scalability, availability, security, and long-term support:

eBook – Persistence – NPI EA (cat=Persistence)

announcement - icon

Working on getting your persistence layer right with Spring?

eBook – Jackson – NPI EA (cat=Jackson)

announcement - icon

Do JSON right with Jackson

eBook – HTTP Client – NPI EA (cat=Http Client-Side)

announcement - icon

Get the most out of the Apache HTTP Client

eBook – Maven – NPI EA (cat = Maven)

announcement - icon

Get Started with Apache Maven:

Course – RwS – NPI EA (cat=REST)

announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

Partner – Lightrun – NPI EA (cat=Spring)

announcement - icon

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Course – LS – NPI EA (cat=Spring)

announcement - icon

Get started with Spring and Spring Boot, through the reference Learn Spring course:

eBook – RwS – NPI EA (cat=Spring MVC)

announcement - icon

Building a REST API with Spring?

Partner – Machinet – NPI EA (cat = Testing)

announcement - icon

The AI Assistant to boost Boost your productivity writing unit tests — Machinet AI.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you’ll get the power of AI-assisted coding and automated unit test generation.
Machinet’s Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.
And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI:

Partner – Codium – NPI EA (cat = Testing)

announcement - icon

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

Partner – Bellsoft – NPI EA (cat = Spring/DevOps)

announcement - icon

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux: lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps. It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

Course – LSS – NPI EA (cat=Spring Security)

announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses — Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

Partner – Aegik AB – NPI EA (tag = SQL)

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Partner – DBSchema – NPI EA (tag = SQL)

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Course – LSD – NPI EA (tag=Spring Data JPA)

announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *