Cannot find symbol java что это

от admin

What is the Cannot Find Symbol Java Error?

The Cannot Find Symbol in Java is a compilation error that occurs when we try to refer to something that is not present in the Java Symbol Table. A very common example of this error is using a variable that is not declared in the program.

Java compilers create and maintain Symbol tables. The symbol table stores the information of the identifiers i.e. classes, interfaces, variables, and methods in the given source of code. When we use these identifiers in our code, the compiler looks up to the symbol table for information. If the identifier is not declared or is not present in the given scope the compiler throws 'Cannot Find Symbol'.

What Causes the Java Cannot Find Symbol Error?

There are multiple ways and reasons this error can occur, they all boil down to the fact that the Java Compiler couldn't find the identifier in the Symbol table. Some of the very commonly made mistakes are listed below:

  • Java is case sensitive, thus hello and Hello are two different variables.
  • If identifiers are misspelled say the variable's name is name and we are trying to access nmae can cause an error.
  • Sometimes variables are declared in a particular iterating loop or method and if we try to call them from outside causes an error as it is out of the scope of the variable.
  • Using variables without their declaration is also the common cause of the Java 'Cannot find Symbol' error.
  • Sometimes we use methods from classes of a different package. To do so we are required to import the package of the class. Missing import statements can cause the error too.
  • Use of underscore, dollar sign, numbers, letter even a character before or after different from the initial declaration can cause 'Cannot Find Symbol'.

Examples of Java Cannot Find Symbol error

Let us now see these common errors in the form of code:

Example 1

Let us take a very simple example of a function that takes user input of a number and returns if the number is even or odd.

In the example above, the Scanner class is not imported and thus it is throwing a Cannot Find Symbol error. The compiler is not able to find Scanner in the program. Once we import the package, it is able to identify the Scanner class.

Example 2

Another example is wrong spelling and undeclared variables. Let us take a simple example where we multiply a variable a few times in a loop.

Output:

In the example above we can see 3 errors, all of them being 'cannot find symbol'. The first one is because N is not declared in the program, and the two are because we declared finalResult but we are calling final_Result . Thus, a single underscore can also cause an error.

Example 3

Lastly, out-of-scope variables also cause a 'Cannot find Symbol' error, below example demonstrates it.

Output:

In the example above, the sum variable is declared inside the for loop and its scope is only inside for loop. As we are trying to access it outside the for loop, it is causing the error.

Structure of Java Cannot Find Symbol

Look at the output generated by the compiler for the 3rd example:

As we can see in the output, the compiler tells the line number of the error as well as points to the variable where the error occurred and the type of the error which is cannot find symbol in this case. The compiler also produces the cannot find symbol including these two additional fields:

  • The very first one is the symbol it is unable to find, i.e. the name and type of the referenced identifier.
  • The other field is the location of the place where the symbol is used. The class and line number are returned where the identifier has been referenced.

Cannot Find Symbol vs Symbol Not Found vs Cannot Resolve Symbol

Different compilers may use slightly different terminologies. The 'Cannot Find Symbol', 'Symbol Not Found', and 'Cannot Resolve Symbol' are all same errors only. Besides the naming, these convey the same meaning to the user and the compiler.

Ошибка компиляции “Не найти символ”

Просмотрите, что такое ошибки компиляции, а затем конкретно объясните, что такое ошибка «не может найти символ» и как она вызвана.

  • Автор записи

1. Обзор

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

2. Ошибки времени компиляции

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

В основном существует три типа ошибок времени компиляции:

  • У нас могут быть синтаксисные . Одна из наиболее распространенных ошибок, которые может сделать любой программист, это забыть поставить заоколонку в конце заявления; некоторые другие забывают импорт, несоответствие скобки, или опуская заявление о возвращении
  • Далее, естьошибки проверки типов. Это процесс проверки безопасности типов в нашем коде. С помощью этой проверки мы убеждаемся, что у нас есть последовательные типы выражений. Например, если мы определяем переменную типа int , мы никогда не должны назначать двойной или Струнные значение для него
  • Между тем, существует вероятность того, что компилятор . Это очень редко, но это может произойти. В этом случае хорошо знать, что наш код не может быть проблемой, но что это скорее внешняя проблема

3. Ошибка “не может найти символ”

Ошибка “не может найти символ” возникает в основном, когда мы пытаемся использовать переменную, которая не определена или объявлена в нашей программе.

Когда наш код компилирует, компилятор должен проверить все идентификаторы, которые у нас есть. Ошибка “не может найти символ” означает, что мы ссылаясь на то, что компилятор не знает о .

3.1. Что может вызвать ошибку «не может найти символ»?

Действительно, есть только одна причина: Компилятор не смог найти определение переменной, на которую мы пытаемся ссылаться.

Но, Есть много причин, почему это происходит. Чтобы помочь нам понять, почему, давайте напомним себе, из чего состоит Java-код.

Наш исходный код Java состоит из:

  • Ключевые слова: правда, ложь, класс, в то время как
  • Буквально: цифры и текст
  • Операторы и другие не-альфа-токены: -,/,
  • Идентификаторы: основные , Читатель , Я , toString и так далее.
  • Комментарии и белое пространство

4. Опечатка

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

  • Струнныйбиулдер
  • строкаСтроитель
  • String_Builder

все это будет по-разному способы неправильно ссылаться на Стрингбилдер класс.

5. Сфера применения экземпляра

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

Допустим, у нас есть Статья класс, который вызывает generateId метод:

Но, мы объявляем generateId метод в отдельном классе:

С помощью этой настройки компилятор даст ошибку “не может найти символ” для generateId на линии 7 Статья обрезок. Причина в том, что синтаксис строки 7 подразумевает, что generateId метод объявляется в Статья .

Как и во всех зрелых языках, существует несколько способов решения этой проблемы. Но, один из способов было бы построить ИдГенератор в Статья класса, а затем вызвать метод:

6. Неопределенные переменные

Иногда мы забываем объявить переменную. Как мы видим из фрагмента ниже, мы пытаемся манипулировать переменной мы не объявили, в данном случае, текстовые :

Мы решаем эту проблему, объявляя переменную текстовые типа Струнные :

7. Переменный охват

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

Переменные внутри цикла недоступны за пределами цикла:

если заявление должно идти внутри для петли если нам нужно изучить символы больше:

8. Недействительное использование методов или полей

Ошибка “не может найти символ” также произойдет, если мы используем поле в качестве метода или наоборот:

Теперь, если мы попытаемся сослаться на тексты поле, как если бы это был метод:

то мы увидим ошибку.

Это потому, что компилятор ищет метод под названием тексты , которого нет.

Вообще-то, есть getter метод, который мы можем использовать вместо этого:

Ошибка работы на массиве, а не элемент массива также является проблемой:

И так забывает новые ключевое слово, как в:

9. Импорт пакетов и классов

Другая проблема заключается в том, чтобы забыть импортировать класс или пакет. Например, с помощью Список объект без импорта java.util.List :

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

10. Неправильный импорт

Импорт неправильного типа, из-за завершения IDE или автоматической коррекции также является общей проблемой.

Подумайте о ситуации, когда мы хотим использовать даты в Java. Много раз мы могли бы импортировать неправильный Дата класс, который не предоставляет методы и функции, как другие классы даты, которые нам могут понадобиться:

Чтобы получить год, месяц или день для java.util.Date , мы также должны импортировать Календарь класса и извлечь информацию оттуда.

Просто ссылаясь на getDate () из java.util.Date не будет работать:

Вместо этого мы используем Календарь объект:

Однако, если мы импортировали Местное класса, нам не нужен дополнительный код, который предоставляет нам информацию, в которой мы нуждаемся:

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

Компиляторы работают над фиксированным набором правил, которые являются специфическими для языка. Если код не придерживается этих правил, компилятор не может выполнить процесс преобразования, что приводит к ошибке компиляции. Когда мы сталкиваемся с ошибкой компиляции “Не может найти символ”, ключ должен определить причину.

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

How to Resolve The Cannot Find Symbol Error in Java

Symbol tables are an important data structure created and maintained by compilers to store information associated with identifiers [1] in a given source code. This information is entered into the symbol tables during lexical and syntax analysis and is used in the later phases of compilation. As the declarations of classes, interfaces, variables, and methods are processed, their identifiers are bound to corresponding entries in the symbol tables. When uses of these identifiers are encountered in the source code, the compiler looks them up in the symbol tables and relies on this information for things such as verifying that a variable has been declared, determining the scope of a variable, and verifying that an expression is semantically correct with type checking. Symbol tables are also used for code generation and optimization [2].

Читать:
Как менять цвет графика в матлаб

A simplified representation of a symbol table entry (or simply, a symbol) in Java has the following format: . Given a global variable declaration like final double ratio; the corresponding symbol would then be .

Cannot Find Symbol Error

As its name implies, the cannot find symbol error refers to a symbol which cannot be found. While there are multiple ways and reasons this can occur, they all boil down to the fact that the Java compiler is unable to find the symbol associated with a given identifier.

The message produced by the compiler for the cannot find symbol error includes two additional fields:

  • “symbol”—the name and type of the referenced identifier; and
  • “location”—the specific class in which the identifier has been referenced.

What Causes the Cannot Find Symbol Error

The most common triggers for the cannot find symbol compile-time error include:

  • missing variable and method declarations;
  • out-of-scope references to variables and methods;
  • misspelled identifiers; and
  • omitted import statements.

Cannot Find Symbol vs Symbol Not Found vs Cannot Resolve Symbol

As different Java compilers use slightly different terminology, the cannot find symbol error can also be found under the terms symbol not found and cannot resolve symbol . Besides the naming, there is no difference between what these terms stand for.

Cannot Find Symbol Error Examples

Undeclared variable

When the Java compiler encounters a use of an identifier which it cannot find in the symbol table, it raises the cannot find symbol error. Consequently, the most common occurrence of this error is when there is a reference to an undeclared variable. Unlike some other languages that don’t require explicit declaration of variables [3], or may allow declaring a variable after it has been referenced (via hoisting [4]), Java requires declaring a variable before it can be used or referenced in any way.

Fig. 1(a) shows how an undeclared variable, in this case the identifier average on line 9, results in two instances of the cannot find symbol error, at the positions where they appear in the code. Declaring this variable by specifying its data type (or, alternatively, inferring its type with the var keyword in Java 10+) resolves the issue (Fig. 1(b)).

Figure 1: Cannot find symbol for undeclared variable (a) error and (b) resolution

Out of scope variable

When a Java program tries to access a variable declared in a different (non-inherited or non-overlapping) scope, the compiler triggers the cannot find symbol error. This is demonstrated by the attempt to access the variable counter on lines 17 and 18 in Fig. 2(a), which is accessible only within the for statement declared on line 11. Moving the counter variable outside the for loop fixes the issue, as shown on Fig. 2(b).

Figure 2: Cannot find symbol for out-of-scope variable reference (a) error and (b) resolution

Misspelled method name

Misspelling an existing method, or any valid identifier, causes a cannot find symbol error. Java identifiers are case-sensitive, so any variation of an existing variable, method, class, interface, or package name will result in this error, as demonstrated in Fig. 3.

Figure 3: Cannot find symbol for misspelled method name (a) error and (b) resolution

Missing import statement

Using classes, either from the Java platform or any library, requires importing them correctly with the import statement. Failing to do so will result in the cannot find symbol error being raised by the Java compiler. The code snippet in Fig. 4(a) makes use of the java.util.List class without declaring the corresponding import, therefore the cannot find symbol error occurs. Adding the missing import statement (line 4 in Fig. 4(b)) solves the problem.

Figure 4: Cannot find symbol for missing import (a) error and (b) resolution

Less common examples

The root cause for the cannot find symbol Java error can occasionally be found in some unexpected or obscure places. Such is the case with accidental semicolons that terminate a statement ahead of time (Fig. 5), or when object creation is attempted without a proper constructor invocation which has to have the new keyword (Fig. 6).

Getting "cannot find Symbol" in Java project in IntelliJ

I make this call to a static singleton instance from the class GameManager.java .

HUD.java contains the HUD class as well as two other related classes, HUDTextElement and HUDElement . All the classes are in the same root path ../src/org/mypackage .

However, when compiling this project in IntelliJ I get cannot find Symbol HUD on the line I make the HUD.getInstance() call.

This exact same code compiles just fine in Eclipse, any idea what the problem is?

31 Answers 31

Select Build->Rebuild Project will solve it

tiboo's user avatar

I had the same problem and fixed it by clicking File>Invalidate caches/ restart

I had the same problem, and turns out I had never completely compiled the fresh project. So right-clicking and selecting Compile» (shift-cmd-F9 on mac) fixed it. It seems the compile on save does not ‘see’ non-compiled files.

Marking the src folder as source did not help in my case.

This is likely to be your ../src folder is not marked as a «source» folder in Intellij IDEA, so it doesn’t know to look there to find your class. You can right click the folder in the project explorer and choose «mark as source folder» to fix this.

Paul Sanwald's user avatar

I was getting the same «cannot find symbol» error when I did Build -> Make Project . I fixed this by deleting my Maven /target folder, right clicking my project module and doing Maven -> Reimport , and doing Build -> Rebuild Project . This was on IntelliJ Idea 13.1.5.

It turns out the Maven -> Reimport was key, since the problem resurfaced a few times before I finally did that.

For me — I tried these steps(Invalidate Cache & Restart, Maven Reimport)) but they didn’t work. So I deleted the .idea , .settings , and .project folder and tried — it worked.

I faced the same problem, and there are a lot of solutions given in the answer, trying all these solutions took me quite some time, so here I would like to propose a methodical approach if you get this error.

Check for the following things, create/update if something is missing

  1. src folder is marked as the source folder
  2. .imls files are present
  3. Annotation processing is enabled
  4. If you recently used @UtilityClass then it can also be the reason, Bug Link

If everything is fine, you can try following solutions in given order

Recompile the file/module

If that didn’t fix the issue, try refreshing maven dependency and building the project using Maven -> Reimport and Build -> Rebuild Project

Try mvn clean install -DskipTests

Try invalidating the IntelliJ cache and restarting the IDE, using File > Invalidate caches/ restart

Delete the .idea folder and reimport the project

Credit and Thanks to everyone who answered this question, you can refer to their answers for more description regarding each point.

Deepak Patankar's user avatar

Thanks for the help so far, turns out the fix was to compile HUD.java first (right click on the file-> Compile HUD.java). After compiling the java file the rest of the project could be compiled without any problems.

I don’t really know why this fixed it, or why IntelliJ wouldn’t do this automatically, but root error seems it has to do with IntelliJ not correctly handling having multiple classes in a single .java file.

This happened to me when I deleted a folder and then copy-pasted it back to the project.

Right-click project folder -> Rebuild worked for me.

I solved this problem doing right click on Java Folder and Rebuild

IntelliJ screenshot

Federico Traiman's user avatar

I had to right-click the project, and select «Reimport» under the «Run Maven» submenu.

I use maven in my project. For some reason IntelliJ was giving me these kind of wierd errors. I ran mvn clean and tried a resync and these errors disappeared.

recompiling the main Application.java class did it for me, right click on class > Recompile

If you are using Lombok, make sure you have enabled annotation processing.

For me was a problem with Lombok, because it requires Annotation Processing to be enabled. You can find this checkbox on Settings > Build > Compiler > Annotation Processors

I know this is an old question, but as per my recent experience, this happens because the build resources are either deleted or Idea cannot recognize them as the source.

Wherever the error appears, provide sources for the folder/directory and this error must be resolved.

Sometimes even when we assign sources for the whole folder, individual classes might still be unavailable. For novice users simple solution is to import a fresh copy and build the application again to be good to go.

It is advisable to do a clean install after this.

Matt's user avatar

I know this thread is old but, another solution was to run

And on IntelliJ do CMD + Shift + A (mac os) -> type «Reimport all Maven projects».

If that doesn’t work, try forcing maven dependencies to be re-downloaded

For me, the error was coming from @RequiredArgsConstructor(onConstructor = @__(@Inject)) , and the message was cannot find symbol __ . The error message right above this was "java: You aren’t using a compiler supported by lombok, so lombok will not work and has been disabled".

Adding argument below in VM options worked as suggested here worked for me.

For my case, the issue was with using Lombok’s experimental feature @UtilityClass in my java project in Intellij Idea, to annotate a class methods as «static». When I explicitly made each method of the class as «static» instead of using the annotation, all the compilation issues disappeared.

Since this is the first hit on Google searching for «intelliJ cannot find symbol» error, I’m gonna throw in my solution as well.

The problem for me was that my project originated from Eclipse, and some files contained dependency on classes that were generated in src/generated-sources by specifications in pom.xml. For some reason, this was not properly executed when I first opened the project and rebuilding/re-importing did not help, so the files were never generated.

The solution was to right-click on the module, and select Maven -> Generate Sources and Update Folders That solved the issue and I could compile.

Похожие статьи