Class is public should be declared in a file named java как исправить

I am trying to write a program, but I'm getting this compiler error: Main.java:1: error: class WeatherArray is public, should be declared in a file named WeatherArray.java public class WeatherArra...

I am trying to write a program, but I’m getting this compiler error:

Main.java:1: error: class WeatherArray is public, should be declared in a file named WeatherArray.java
public class WeatherArray {
       ^
1 error

I have checked my file names, and my public class is the same as my .java file.

How can I fix this?

Here is my code:

public class WeatherArray {
    public static void main(String[] args) {
        // ...
    }
}

Bernhard Barker's user avatar

asked Dec 10, 2012 at 23:22

Chris Frank's user avatar

8

Name of public class must match the name of .java file in which it is placed (like public class Foo{} must be placed in Foo.java file). So either:

  • rename your file from Main.java to WeatherArray.java
  • rename the class from public class WeatherArray { to public class Main {

Pshemo's user avatar

Pshemo

121k25 gold badges182 silver badges265 bronze badges

answered Dec 10, 2012 at 23:25

jlordo's user avatar

jlordojlordo

37.2k6 gold badges58 silver badges81 bronze badges

4

The name of the public class within a file has to be the same as the name of that file.

So if your file declares class WeatherArray, it needs to be named WeatherArray.java

answered Dec 10, 2012 at 23:25

BostonJohn's user avatar

BostonJohnBostonJohn

2,5712 gold badges26 silver badges48 bronze badges

This happens when you have 1 name for the Java class on hard disk and another name of Java class in the code!!

For example, I renamed my MainActivity class to MainnActivity only (!) in the code. I got this error immediately.

There is also a visual indicator in the Project tab of Android Studio — a class inside a class, like you have nested classed, but with an error indicator.

The solution is to simply rename class name in the Project tab (SHIFT + F6) to match the name in the Java code.

answered Jul 15, 2015 at 13:05

sandalone's user avatar

sandalonesandalone

40.8k63 gold badges219 silver badges334 bronze badges

I had the same problem but solved it when I realized that I didn’t compile it with the correct casing. You may have been doing

javac Weatherarray.java

when it should have been

javac WeatherArray.java

answered Aug 27, 2019 at 20:57

Warren Feeney's user avatar

You named your file as Main.java. name your file as WeatherArray.java and compile.

answered Dec 10, 2012 at 23:26

PermGenError's user avatar

PermGenErrorPermGenError

45.7k8 gold badges86 silver badges106 bronze badges

your file is named Main.java where it should be

WeatherArray.java

answered Dec 10, 2012 at 23:27

AlexWien's user avatar

AlexWienAlexWien

28.2k6 gold badges52 silver badges80 bronze badges

Yes! When you face these type of problem then try to following points

  • Check Your .java file name and class name.
  • If Class name and public class name are not the same then RENAME class name.

Ahmet Emre Kilinc's user avatar

answered Sep 2, 2022 at 20:51

Yuvraj Singh's user avatar

I my case, I was using syncthing. It created a duplicate that I was not aware of and my compilation was failing.

answered Jan 30, 2018 at 22:04

abc123's user avatar

abc123abc123

5275 silver badges16 bronze badges

To avoid this error you should follow the following steps:

1) You should make a new java class

You should make a new java class.

2) Name that class

Name that class

3) And a new java class is made

And a new java class is made

André Kool's user avatar

André Kool

4,84012 gold badges33 silver badges44 bronze badges

answered Mar 12, 2018 at 15:45

Rahat Batool's user avatar

I encountered the same error once. It was really funny. I had created a backup of the .java file with different filename but the same class name. And kept on trying to build it till I checked all the files in my folder.

answered May 3, 2018 at 16:18

Yash P Shah's user avatar

Yash P ShahYash P Shah

78311 silver badges15 bronze badges

In my case (using IntelliJ) I copy and pasted and renamed the workspace, and I am still using the old path to compile the new project.

In this case this particular error will happen too, if you have the same error you can check if you have done the similar things.

answered Jul 16, 2018 at 4:42

Ng Sek Long's user avatar

Ng Sek LongNg Sek Long

3,9152 gold badges30 silver badges37 bronze badges

The terminal is not case sensitive when writing «Javac [x].java», so make sure what you write in the terminal matches the filename and class name.

My class name and file name were both «MainClass», but I was compiling using «Mainclass». Notice I forgot to make the «c» capital.

answered Jan 25, 2019 at 15:21

Dylan's user avatar

DylanDylan

3452 silver badges12 bronze badges

From Ubuntu command line:

//WeatherArray.java
public class WeatherArray {
  public static void main(String[] args) {
    System.out.println("....Hello World");
}}

ls

WeatherArray.java

javac WeatherArray.java

ls

WeatherArray.java WeatherArray.class

java WeatherArray

….Hello World

Of course if you name your java file with different name than WeatherArray, you need to take out public and it would be:

// Sunny.java
class WeatherArray {
   public static void main(String[] args) {
      System.out.println("....Hello World"); }}
// javac Sunny.java; java WeatherArray

Community's user avatar

answered Jan 9, 2020 at 16:37

NotTooTechy's user avatar

NotTooTechyNotTooTechy

4025 silver badges8 bronze badges

If you make WeatherArray class from public to default.

public class WeatherArray =====> class WeatherArray

then you do not get any error and
you can easily compile your code by just writing

==> javac any_name_you_assign_to_file.java

Now a WeatherArray.class will generate.

To run your code you have to use class name

==> java WeatherArray

answered Jun 30, 2021 at 19:47

Sachin Singh's user avatar

Compile WeatherArray.java instead of Main.java

This error comes if you have not saved your source code with the same name of your public class name.

answered Jul 13, 2021 at 13:01

iamfnizami's user avatar

iamfnizamiiamfnizami

1431 silver badge8 bronze badges

If your class name is the same as the filename then check that it does not contain any zero width character

I accidentally copied a class name with invisible whitespace which caused this exception

Eclipse was able to build the file and Gradle was not

This can be very confusing

answered Sep 11, 2021 at 20:50

answer42's user avatar

The answer is quite simple. It lies in your admin rights. before compiling your java code you need to open the command prompt with run as administrator. then compile your code. no need to change anything in your code. the name of the class need to be the same as the name of the java file.. that’s it!!

answered Jun 23, 2015 at 20:28

Rohan Kumar's user avatar

1

error example:

public class MaainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);

  }
}

correct example:just make sure that you written correct name of activity that is»main activity»

public class MainActivity extends Activity {


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);

  }
}

jHilscher's user avatar

jHilscher

1,7902 gold badges24 silver badges29 bronze badges

answered Apr 12, 2017 at 9:06

dhiraja gunjal's user avatar

1

when you named your file WeatherArray.java,maybe you have another file on hard disk ,so you can rename WeatherArray.java as ReWeatherArray.java, then rename ReWeatherArray.java as WeatherArray.java. it will be ok.

answered Jul 27, 2016 at 9:46

Sangoo's user avatar

2

  1. Cause of the class X is public, should be declared in a file named X.java Error
  2. Fix the class X is public, should be declared in a file named X.java Error

Fix Class X Is Public Should Be Declared in a File Named X.java Error

Today, we will go through various stages, starting from demonstrating a compile time error stating class X is public should be declared in a file named X.java. Then, we will see the reason causing this error, which will lead to its solution via code example.

Cause of the class X is public, should be declared in a file named X.java Error

Example Code Containing the Specified Error (Main.java file):

public class Test{
    public static void main(String[] param){
        HiWorld();
        System.exit(0);
    }


    public static void HiWorld(){
        System.out.println("Hi World");
    }
}

We have this code in a file named Main.java while the class name is Test. Now, compile the code using the javac command as follows.

As soon as we press the Enter key, it gives the following error.

Main.java:1: error: class Test is public, should be declared in a file named Test.java
public class Test{
       ^
1 error

What does this error mean? Why is it occurring? It means that we must have the public class named Test in the Test.java file, but in our case, we have it in the Main.java file.

That’s the only reason for this error. How to fix this? We can get rid of it in the following two ways.

Fix the class X is public, should be declared in a file named X.java Error

Rename the File

To fix this error, rename the file as Test.java, which contains the Test class as given below.

Example Code (Test.java file):

public class Test{
    public static void main(String[] param){
        HiWorld();
        System.exit(0);
    }

    public static void HiWorld(){
        System.out.println("Hi World");
    }
}

Compile the Code:

Run the Code:

OUTPUT:

Rename the Class

We can keep the file name as Main.java for the second solution but rename the class as Main. See the code snippet below.

Example Code (Main.java file):

public class Main{
    public static void main(String[] param){
        HiWorld();
        System.exit(0);
    }

    public static void HiWorld(){
        System.out.println("Hi World");
    }
}

Compile the Code:

Run the Code:

OUTPUT:

Здравствуйте.
С самой ошибкой я разобрался. Убрал public, оставил его только для GameLauncher и всё скомпилилось и завелось.
Вопрос в другом.
Какой класс правильно объявить публичным?
И почему в книге пример с ошибками (код был из книги)? Возможно связано с тем что книга по java 5.
Буду очень благодарен, если объясните по какому принципу объявлять класс публичным и почему так вышло с примеров книги.

Моя версия JSE
java version «13.0.1» 2019-10-15
Java(TM) SE Runtime Environment (build 13.0.1+9)
Java HotSpot(TM) 64-Bit Server VM (build 13.0.1+9, mixed mode, sharing)

Ошибка при компиляции. Использую javac без каких либо IDE.
GameLauncher.java:1: error: class GuessGame is public, should be declared in a file named GuessGame.java
public class GuessGame {
^
GameLauncher.java:61: error: class Player is public, should be declared in a file named Player.java
public class Player {
^
2 errors

Сам код из книги

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
public class GuessGame {
    Player p1;
    Player p2;
    Player p3;
 
    public void startGame() {
        p1 = new Player();
        p2 = new Player();
        p3 = new Player();
 
        int guessp1 = 0;
        int guessp2 = 0;
        int guessp3 = 0;
 
        boolean p1isRight = false;
        boolean p2isRight = false;
        boolean p3isRight = false;
 
        int targetNumber = (int) (Math.random() * 10);
        System.out.println("Я загадываю число от 0 до 9...");
 
        while(true) {
            p1.guess();
            p2.guess();
            p3.guess();
 
            guessp1 = p1.number;
            System.out.println("Первый игрок думает что это " + guessp1);
 
            guessp2 = p2.number;
            System.out.println("Второй игрок думает что это " + guessp2);
            
            guessp3 = p3.number;
            System.out.println("Третий игрок думает что это " + guessp3);
 
            if (guessp1 == targetNumber) {
                p1isRight = true;
            }
            if (guessp2 == targetNumber) {
                p2isRight = true;
            }
            if (guessp3 == targetNumber) {
                p3isRight = true;
            }
 
            if (p1isRight || p2isRight || p3isRight) {
 
                System.out.println("У нас есть победитель!");
                System.out.println("Первый игрок угадал? " + p1isRight);
                System.out.println("Второй игрок угадал? " + p2isRight);
                System.out.println("Третий игрок угадал? " + p3isRight);
                System.out.println("Конец игры");
                break;
            } else {
                System.out.println("Игроки должны попробовать ещё раз.");
            }
        }
    }
}
 
public  class Player {
    int number = 0;
    public void guess() {
        number = (int)(Math.random() * 10);
        System.out.println("Думаю что это число " + number);
    }
}
 
public class GameLauncher {
    public static void main(String[] args) {
        GuessGame game = new GuessGame();
        game.startGame();
    }
}

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

Вопрос №142 от пользователя Игорь Рыжов в уроке «Модуль 1. Урок 5. Настройка окружающей среды для разработки на языке Java.», курс «Введение в Java»

Игорь Рыжов

При попытке компиляции ругается на необъявленный класс. При этом в IDE все ОК. Почему так? (Windows)

$ javac main.java
main.java:2: error: class Main is public, should be declared in a file named Main.java
public class Main {
       ^
1 error


3


0

R. D.

Причина написана в сообщении: «class Main is public, should be declared in a file named Main.java»
Ваш файл называется main.java, а должен называться Main.java


2

Юлий Афанасьев

Если рядом нет файла Main.java появляется подобное сообщение. Что делать? Win


0

Роман Черепанов

Переименуй main.java на Main.java


2

Используйте Хекслет по-максимуму!


  • Задавайте вопросы по уроку

  • Проверяйте знания в квизах

  • Проходите практику прямо в браузере

  • Отслеживайте свой прогресс

Зарегистрируйтесь или
войдите в свой аккаунт

Рекомендуемые программы

С нуля до разработчика. Возвращаем деньги, если не удалось найти работу.

Иконка программы Фронтенд-разработчик

Разработка фронтенд-компонентов для веб-приложений



9 февраля



10 месяцев

Иконка программы Онлайн-буткемп. Фронтенд-разработчик

Интенсивное обучение профессии в режиме полного дня



9 февраля



4 месяца

Иконка программы Python-разработчик

Разработка веб-приложений на Django



9 февраля



10 месяцев

Иконка программы Java-разработчик

Разработка приложений на языке Java



9 февраля



10 месяцев

Иконка программы PHP-разработчик

Разработка веб-приложений на Laravel



9 февраля



10 месяцев

Иконка программы Инженер по тестированию

Ручное тестирование веб-приложений



9 февраля



4 месяца

Иконка программы Node.js-разработчик

Разработка бэкенд-компонентов для веб-приложений



9 февраля



10 месяцев

Иконка программы Fullstack-разработчик

Разработка фронтенд- и бэкенд-компонентов для веб-приложений



9 февраля



16 месяцев

Иконка программы Разработчик на Ruby on Rails

Создание веб-приложений со скоростью света



9 февраля



5 месяцев

Иконка программы Верстальщик

Верстка с использованием последних стандартов CSS



в любое время



5 месяцев

Иконка программы Аналитик данных

Профессия

В разработке
с нуля

Сбор, анализ и интерпретация данных



16 марта



8 месяцев

PROBLEM:

  • When the class name and the filename of a given Java program doesn’t match then we will get this error.
  • Considering an example where the file is named as wiki.java

[pastacode lang=”java” manual=”public%20class%20techy%20%0A%7B%20%20%20%20%20%0A%20%20%20%20%20%20%20%20public%20static%20void%20main(String%5B%5D%20args)%20%0A%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20System.out.println(%22Hello%2C%20wikitechy!%22)%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%09%0A” message=”java code” highlight=”” provider=”manual”/]

1 error found:

File: wiki.java  [line: 1]

Error: class techy is public, should be declared in a file named wiki.java

SOLUTION 1:

  • Since wiki does not match with techy, the code will not compile properly. To fix this error kind of error, either we need to rename the file or change the class name as “wiki.java”
  • As the error message suggests, if we declare a class as public, it needs its wiki.java file. If we don’t want to do that, we don’t define it as public.

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I’m a frequent speaker at tech conferences and events.

Related Tags
  • 8) error: class funfactsactivity is public,
  • android studio class is public should be declared in a file named,
  • arrays — Java class is public should be declared in a file named,
  • Class is public,
  • class names are only accepted if annotation,
  • error: cannot find symbol,
  • Error: class is public,
  • error: could not find or load main class helloworld,
  • error: could not find or load main class main,
  • Error:(9,
  • how to declare file in java,
  • j2me error: class myClass is public should be declared in a file named,
  • Java Error: class is public,
  • Java Error: Should be declared in a file named,
  • javascript — Class is public,
  • main method not found in class,
  • modifier private not allowed here,
  • should be declared,
  • should be declared in a file named .java,
  • should be declared in a file named .java public,
  • should be declared in a file?

Я пытаюсь написать программу, но я получаю эту ошибку компилятора:

Main.java:1: error: class WeatherArray is public, should be declared in a file named WeatherArray.java
public class WeatherArray {
       ^
1 error

Я проверил мои имена файлов, и мой открытый класс такой же, как мой.java файл.

Как я могу это исправить?

Вот мой код:

public class WeatherArray {
    public static void main(String[] args) {
        // ...
    }
}

4b9b3361

Ответ 1

Имя открытого класса должно совпадать с именем файла .java, в котором он находится (например, public class Foo{} должен быть помещен в файл Foo.java). Так что либо:

  • переименуйте ваш файл с Main.java на WeatherArray.java
  • переименуйте класс из public class WeatherArray { в public class Main {

Ответ 2

Имя открытого класса в файле должно быть таким же, как имя этого файла.

Поэтому, если ваш файл объявляет класс WeatherArray, его нужно называть WeatherArray.java

Ответ 3

Это происходит, когда у вас есть 1 имя для класса Java на жестком диске и другое имя класса Java в коде !!

Например, я переименовал свой класс MainActivity в MainnActivity (!) Только в коде. Я получил эту ошибку немедленно.

На вкладке «Проект» в Android Studio есть визуальный индикатор — класс внутри класса, например, вы вложенные классы, но с индикатором ошибки.

Решение состоит в том, чтобы просто переименовать имя класса на вкладке «Проект» (SHIFT + F6), чтобы совместить имя в коде Java.

Ответ 4

Вы назвали свой файл Main.java. назовите свой файл как WeatherArray.java и скомпилируйте.

Ответ 5

ваш файл называется Main.java, где он должен быть

WeatherArray.java

Ответ 6

У меня была та же проблема, но я решил ее, когда понял, что не скомпилировал ее с правильным корпусом. Возможно, вы занимались

javac Weatherarray.java

когда это должно было быть

javac WeatherArray.java

Ответ 7

Я в моем случае, я использовал syncthing. Он создал дубликат, о котором я не знал, и моя компиляция не срабатывала.

Ответ 8

Чтобы избежать этой ошибки, выполните следующие действия:

1) You should make a new java class

You should make a new java class.

2) Name that class

Name that class

3) And a new java class is made

And a new java class is made

Ответ 9

Однажды я столкнулся с такой же ошибкой. Это было действительно смешно. Я создал резервную копию файла.java с другим именем файла, но с тем же именем класса. И продолжал пытаться построить его, пока не проверил все файлы в моей папке.

Ответ 10

В моем случае (используя IntelliJ) я копирую и вставляю и переименовываю рабочее пространство, и я все еще использую старый путь для компиляции нового проекта.

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

Ответ 11

Терминал не учитывает регистр при написании «Javac [x].java», поэтому убедитесь, что то, что вы пишете в терминале, соответствует имени файла и имени класса.

Мои имя класса и имя файла были «MainClass», но я компилировал с использованием «Mainclass». Заметьте, я забыл сделать заглавную букву «с».

Ответ 12

Ответ довольно прост! Он лежит в ваших правах администратора. перед компиляцией java-кода вам нужно открыть командную строку, запустив ее как администратор. затем скомпилируйте свой код. не нужно ничего менять в коде. имя класса должно быть таким же, как имя java файла.. это!

Ответ 13

когда вы назвали ваш файл WeatherArray.java, может быть, у вас есть еще один файл на жестком диске, так что вы можете переименовать WeatherArray.java в ReWeatherArray.java, а затем переименовать ReWeatherArray.java в WeatherArray.java. все будет хорошо.

Ответ 14

пример ошибки:

public class MaainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);

  }
}

правильный пример: просто убедитесь, что вы написали правильное название деятельности, которое является «основным видом деятельности»,

public class MainActivity extends Activity {


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);

  }
}

So I’m running a program called BankAccount.java. When I tried to comile it (javac BankAccount.java) I get a message that says

BankAccount.java:4:class InsufficientFundsException is public, should be declared in a file named InsufficientFundsException.java
public class InsufficientFundsException extends Exception
^
1 error

In case you need to see it, my code is

import java.util.*;
import java.text.*;

public class InsufficientFundsException extends Exception
{
private int accountNumber;
private int withdrawAmount;
private int balanceAmount;
private Date date;
private DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
private NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

public InsufficientFundsException(int actNumb,
int amount,
int balance)
{
date = new Date();
accountNumber = actNumb;
withdrawAmount = amount;
balanceAmount = balance;
}

public String toString()
{
return getClass().getName() + » on » + df.format(date)
+ «. Withdraw of » + nf.format(withdrawAmount)
+ » rejected. Balance of account #» + accountNumber
+ » remains at » + nf.format(balanceAmount) ;
}
}

160x600 Hire Freelancers

Search entire site:

Looking for a DevOps or I.T. job? Try ZipRecruiter.

Interested in Bitcoin Competitors but only have US dollars?

Coinbase has many different coins; you can often get $5 of cryptocurrency free if you sign up with Coinbase.

Want to invest in over 150 cryptocurrencies (e.g. altcoins) besides Bitcoin directly with U.S. dollars?  No need to be concerned about trading pairs as long as you have US dollars for over 150 altcoin types.  Try Changelly. (Changelly and Coinbase are not related.)

Continual Integration Recommendations

Would you like to be part of ContinualIntegration.com’s mailing list?  Provide your email address below.

Want your career to move toward cryptocurrency?

Archives

Archives

Categories

Categories


When browsing this website from a VPN IP address, some [useful] advertisement links may not work when clicked as normal. Consider turning off your VPN to click on an ad. Please use the Contact page if there are other problems. The privacy policy is here.

160x600 Fiverr Pro

Понравилась статья? Поделить с друзьями:
  • Clash of clans как изменить вид деревни
  • Clarke error grid
  • Clang fatal error iostream file not found
  • Clang error unsupported option fopenmp
  • Clang error no such file or directory