Cannot resolve symbol println как исправить

Intellij is giving me this error for scala code: Cannot resolve symbol "println" Project Settings: Project SDK: Intellij IDEA Community Edition IC-141.2735.5(openjdk version "1.8")

Intellij is giving me this error for scala code:

    Cannot resolve symbol "println"

Project Settings:

Project SDK:

  Intellij IDEA Community Edition IC-141.2735.5(openjdk version "1.8")

Project Language Level:

  8 - Lambdas, type annotations etc. 

Platform Settings:

SDKs:

   1.8   /usr/lib/jvm/java-8-openjdk-amd64

   IntelliJ IDEA Community Edition IC-141.2735.5

Global Libraries:

   scala-sdk-2.11.6

EDIT:

The compiler reports that println has multiple implementations:

    scala-lang:scala-library:2.11.6.jar
    scala-lang:scala-library:2.11.6.jar

What does this mean?

asked Oct 15, 2015 at 16:36

user2827214's user avatar

user2827214user2827214

1,1811 gold badge13 silver badges31 bronze badges

8

I don’t know whether it’s still relevant but I just had the same problem. For me, it worked to just re-add the Scala SDK under «Global Libraries»: Delete it using the red minus sign and then, with the green plus sign, add Scala SDK again.

Cheers

answered Feb 5, 2016 at 13:34

Nico's user avatar

NicoNico

1512 silver badges6 bronze badges

public class Nurse extends Employee {
    public Nurse(boolean working, long id, String name, String department) {
        super(working, id, name, department);

        // here println can be resolved. Because it's inside of a function.
        System.out.println("Invoking constructor "); 
    }

   // System.out.println("Some messge "); // here println can't be resolved.
}

answered Aug 15, 2016 at 3:51

romanlukichev's user avatar


posted 15 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Hello. I want this program to write a String, an Integer, a Float, and a Character on separate lines in a Random Access File. I went on the java-sun website and decided to experiment with the println() method.

…but the complier tells me: cannot resolve symbol method println(). Why?

Olly


posted 15 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

In the api, there isn’t a method named «println» in the class RandomAccessFile. If you want to write something to the file, you can use the methods headed «write».

Olivier Legat

Ranch Hand

Posts: 176

Mac
Chrome
Windows


posted 15 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Yes, I know. But the only problem with the write() method is that it sticks all the variables in one line. I want to put each variable on a separate line. I know that I can just do something like:

raf.writeInt(the_integer);
raf.writeBytes(«n»);
etc…

But I want to know if there’s an alternative.

Olly


posted 15 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Originally posted by Olivier Legat:
I want to put each variable on a separate line. I know that I can just do something like:

raf.writeInt(the_integer);
raf.writeBytes(«n»);
etc…

But I want to know if there’s an alternative.

If that is all you want, why can’t you just write a method for it? Write you own println(), that takes a parameter, which… writes the parameter then write the CRLF.

Henry
[ November 24, 2007: Message edited by: Henry Wong ]

Olivier Legat

Ranch Hand

Posts: 176

Mac
Chrome
Windows


posted 15 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Yes. I’ve thought of doing that, but I just wanted to make sure that there isn’t already a pre-defined method that does that.

Olly


posted 15 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

println() doesn’t make logical sense for a Random Access File — there is no concept of «line» in files that are random access.

If you want your data 0x00 terminated or «n» terminated in sections that don’t «use the whole block» that’s just convention.

Bill Shirley — bshirley — frazerbilt.com

if (Posts < 30) you.read( JavaRanchFAQ);

Introduction to Symbol Tables

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: <symbol name (identifier), type, scope, [attributes]>. Given a global variable declaration like final double ratio; the corresponding symbol would then be <ratio, double, global, [final]>.

Install the Java SDK to identify and fix exceptions

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)).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

public class UndeclaredVariable {
    public static void main(String... args) {
        int x = 6;
        int y = 10;
        int z = 32;

        average = (x + y + z) / 3.0; // average is not declared
        System.out.println(average);
    }
}
UndeclaredVariable.java:9: error: cannot find symbol
    average = (x + y + z) / 3.0;
    ^
  symbol:   variable average
  location: class UndeclaredVariable

UndeclaredVariable.java:10: error: cannot find symbol
    System.out.println(average);
                       ^
  symbol:   variable average
  location: class UndeclaredVariable
2 errors

(b)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

public class UndeclaredVariable {
    public static void main(String... args) {
        int x = 6;
        int y = 10;
        int z = 32;

        double average = (x + y + z) / 3.0;
        System.out.println(average);
    }
}
16.0
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).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package rollbar;

import java.util.Arrays;
import java.util.List;

public class OutOfScopeVariable {
    public static void main(String... args) {
        final List<String> strings = Arrays.asList("Hello", "World");
        final String searchFor = "World";

        for (int counter = 0; counter < strings.size(); counter++) {
            if (strings.get(counter).equals(searchFor)) {
                break;
            }
        }

        if (counter < strings.size()) {
            System.out.println("The word " + searchFor + " was found at index " +    counter);
        } else {
            System.out.println("The word " + searchFor + " wasn't found");
        }
    }
}
OutOfScopeVariable.java:17: error: cannot find symbol
    if (counter < strings.size()) {
        ^
  symbol:   variable counter
  location: class OutOfScopeVariable

OutOfScopeVariable.java:18: error: cannot find symbol
      System.out.println("The word " + searchFor + " was found at index " + counter);
                                                                            ^
  symbol:   variable counter
  location: class OutOfScopeVariable
2 errors

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

import java.util.Arrays;
import java.util.List;

public class OutOfScopeVariable {
    public static void main(String... args) {
        final List<String> strings = Arrays.asList("Hello", "World");
        final String searchFor = "World";
        int counter;

        for (counter = 0; counter < strings.size(); counter++) {
            if (strings.get(counter).equals(searchFor)) {
                break;
            }
        }

        if (counter < strings.size()) {
            System.out.println("The word " + searchFor + " was found at index " + counter);
        } else {
            System.out.println("The word " + searchFor + " wasn't found");
        }
    }
}
The word ‘World’ was found at index 1
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.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class MisspelledMethodName {
    static int fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String... args) {
        int fib20 = Fibonacci(20); // Fibonacci ≠ fibonacci
        System.out.println(fib20);
    }
}
MisspelledMethodName.java:11: error: cannot find symbol
    int fib20 = Fibonacci(20);
                ^
  symbol:   method Fibonacci(int)
  location: class MisspelledMethodName

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class MisspelledMethodName {
    static int fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String... args) {
        int fib20 = fibonacci(20);
        System.out.println(fib20);
    }
}
6765
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.

(a)

package rollbar;

import java.util.Arrays;

public class MissingImportList {
    private static final List<String> CONSTANTS = Arrays.asList("A", "B", "C");

    public static void main(String... args) {
        System.out.println(CONSTANTS);
    }
}
MissingImportList.java:6: error: cannot find symbol
  private static final List<String> CONSTANTS = Arrays.asList("A", "B", "C");
                       ^
  symbol:   class List
  location: class MissingImportList

(b)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

import java.util.Arrays;
import java.util.List;

public class MissingImportList {
    private static final List<String> CONSTANTS = Arrays.asList("A", "B", "C");

    public static void main(String... args) {
        System.out.println(CONSTANTS);
    }
}
[A, B, C]
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).

(a)

package rollbar;

public class LoopScope {
public static void main(String... args) {
        int start = 1, end = 10;
        for (int i = start; i <= end; i++); {
            System.out.print(i == end ? i : i + ", ");
        }
    }
}
LoopScope.java:7: error: cannot find symbol
      System.out.print(i == end ? i : i + ", ");
                       ^
  symbol:   variable i
  location: class LoopScope

LoopScope.java:7: error: cannot find symbol
      System.out.print(i == end ? i : i + ", ");
                                  ^
  symbol:   variable i
  location: class LoopScope

LoopScope.java:7: error: cannot find symbol
      System.out.print(i == end ? i : i + ", ");
                                      ^
  symbol:   variable i
  location: class LoopScope
3 errors

(b)

package rollbar;

public class LoopScope {
    public static void main(String... args) {
        int start = 1, end = 10;
        for (int i = start; i <= end; i++) {
            System.out.print(i == end ? i : i + ", ");
        }
    }
}
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Figure 5: Cannot find symbol for prematurely terminated for loop (a) error and (b) resolution

(a)

package rollbar;

public class ObjectCreation {
    public static void main(String... args) {
        String s = String("Hello World!");
        System.out.println(s);
    }
}
ObjectCreation.java:5: error: cannot find symbol
    String s = String("Hello World!");
               ^
  symbol:   method String(String)
  location: class ObjectCreation

(b)

package rollbar;

public class ObjectCreation {
    public static void main(String... args) {
        String s = new String("Hello World!");
        System.out.println(s);
    }
}
Hello World!
Figure 6: Cannot find symbol constructor call (a) error and (b) resolution

Other causes for the cannot find symbol error may include:

  • using dependencies with old or incompatible versions;
  • forgetting to recompile a program;
  • building a project with an older JDK version;
  • redefining platform or library classes with the same name;
  • the use of homoglyphs in identifier construction that are difficult to tell apart;
  • etc.

Conclusion

The cannot find symbol error, also found under the names of symbol not found and cannot resolve symbol, is a Java compile-time error which emerges whenever there is an identifier in the source code which the compiler is unable to work out what it refers to. As with any other compilation error, it is crucial to understand what causes this error, pinpoint the issue and address it properly. In the majority of cases, referencing undeclared variables and methods, including by way of misspelling them or failing to import their corresponding package, is what triggers this error. Once discovered, resolution is pretty straightforward, as demonstrated in this article.

Track, Analyze and Manage Errors With Rollbar

![Rollbar in action](https://rollbar.com/wp-content/uploads/2022/04/section-1-real-time-errors@2x-1-300×202.png)

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] Rollbar, 2021. Handling the <Identifier> Expected Error in Java. Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-handle-the-identifier-expected-error-in-java/. [Accessed Nov. 22, 2021].

[2] ITL Education Solutions Limited, Principles of Compiler Design (Express Learning), 1st ed. New Delhi: Pearson Education (India), 2012.

[3] Tutorialspoint.com, 2021. Python — Variable Types. [Online]. Available: https://www.tutorialspoint.com/python/python_variable_types.htm. [Accessed: Nov. 23, 2021].

[4] JavaScript Tutorial, 2021. JavaScript Hoisting Explained By Examples. [Online]. Available: https://www.javascripttutorial.net/javascript-hoisting/. [Accessed: Nov. 23, 2021]

Query:

Please explain the following about “Cannot find symbol”, “Cannot resolve symbol” or “Symbol not found” errors (in Java).

“Cannot find symbol”, “Cannot resolve symbol” and “Symbol not found” all mean the same thing. Different Java compilers use different phraseology.

Firstly, it is a compilation error1. It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.

Your Java source code consists of the following things:

  • Keywords: like classwhile, and so on.
  • Literals: like truefalse42'X' and "Hi mum!".
  • Operators and other non-alphanumeric tokens: like +={, and so on.
  • Identifiers: like ReaderitoStringprocessEquibalancedElephants, and so on.
  • Comments and whitespace.

A “Cannot find symbol” error is about the identifiers. When your code is compiled, the compiler needs to work out what each and every identifier in your code means.

A “Cannot find symbol” error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn’t understand.

What can cause a “Cannot find symbol” error?

As a first order, there is only one cause. The compiler looked in all of the places where the identifier should be defined, and it couldn’t find the definition. This could be caused by a number of things. The common ones are as follows:

  • For identifiers in general:
    • Perhaps you spelled the name incorrectly; i.e. StringBiulder instead of StringBuilder. Java cannot and will not attempt to compensate for bad spelling or typing errors.
    • Perhaps you got the case wrong; i.e. stringBuilder instead of StringBuilder. All Java identifiers are case sensitive.
    • Perhaps you used underscores inappropriately; i.e. mystring and my_string are different. (If you stick to the Java style rules, you will be largely protected from this mistake …)
    • Perhaps you are trying to use something that was declared “somewhere else”; i.e. in a different context to where you have implicitly told the compiler to look. (A different class? A different scope? A different package? A different code-base?)
  • For identifiers that should refer to variables:
    • Perhaps you forgot to declare the variable.
    • Perhaps the variable declaration is out of scope at the point you tried to use it. (See example below)
  • For identifiers that should be method or field names:
    • Perhaps you are trying to refer to an inherited method or field that wasn’t declared in the parent / ancestor classes or interfaces.
    • Perhaps you are trying to refer to a method or field that does not exist (i.e. has not been declared) in the type you are using; e.g. "rope".push()2.
    • Perhaps you are trying to use a method as a field, or vice versa; e.g. "rope".length or someArray.length().
    • Perhaps you are mistakenly operating on an array rather than array element; e.g. String strings[] = ... if (strings.charAt(3)) { ... } // maybe that should be 'strings[0].charAt(3)'
  • For identifiers that should be class names:
    • Perhaps you forgot to import the class.
    • Perhaps you used “star” imports, but the class isn’t defined in any of the packages that you imported.
    • Perhaps you forgot a new as in: String s = String(); // should be 'new String()'
  • For cases where type or instance doesn’t appear to have the member (e.g. method or field) you were expecting it to have:
    • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.
    • Perhaps you are shadowing a static or instance variable.
    • Perhaps you imported the wrong type; e.g. due to IDE completion or auto-correction may have suggested java.awt.List rather than java.util.List.
    • Perhaps you are using (compiling against) the wrong version of an API.
    • Perhaps you forgot to cast your object to an appropriate subclass.
    • Perhaps you have declared your variable’s type to be a supertype of the one with the member you are looking for.

The problem is often a combination of the above. For example, maybe you “star” imported java.io.* and then tried to use the Files class … which is in java.nio not java.io. Or maybe you meant to write File … which is a class in java.io.


Here is an example of how incorrect variable scoping can lead to a “Cannot find symbol” error:

List<String> strings = ...

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a “Cannot find symbol” error for i in the if statement. Though we previously declared i, that declaration is only in scope for the for statement and its body. The reference to i in the if statement cannot see that declaration of i. It is out of scope.

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.)


Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable “Cannot find symbol” error:

for (int i = 0; i < 100; i++); {
    System.out.println("i is " + i);
}

This will give you a compilation error in the println call saying that i cannot be found. But (I hear you say) I did declare it!

The problem is the sneaky semicolon ( ; ) before the {. The Java language syntax defines a semicolon in that context to be an empty statement. The empty statement then becomes the body of the for loop. So that code actually means this:

for (int i = 0; i < 100; i++); 

// The previous and following are separate statements!!

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, and therefore the previous declaration of i in the for statement is out of scope in the block.


Here is another example of “Cannot find symbol” error that is caused by a typo.

int tmp = ...
int res = tmp(a + b);

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous. The compiler will look for a method called tmp, and won’t find one. The previously declared tmp is in the namespace for variables, not the namespace for methods.

In the example I came across, the programmer had actually left out an operator. What he meant to write was this:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line. You might simply have forgotten to compile or recompile some other class. For example, if you have classes Foo and Bar where Foo uses Bar. If you have never compiled Bar and you run javac Foo.java, you are liable to find that the compiler can’t find the symbol Bar. The simple answer is to compile Foo and Bar together; e.g. javac Foo.java Bar.java or javac *.java. Or better still use a Java build tool; e.g. Ant, Maven, Gradle and so on.

There are some other more obscure causes too … which I will deal with below.

How do I fix these errors ?

Generally speaking, you start out by figuring out what caused the compilation error.

  • Look at the line in the file indicated by the compilation error message.
  • Identify which symbol that the error message is talking about.
  • Figure out why the compiler is saying that it cannot find the symbol; see above!

Then you think about what your code is supposed to be saying. Then finally you work out what correction you need to make to your source code to do what you want.

Note that not every “correction” is correct. Consider this:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says “Cannot find symbol” for j. There are many ways I could “fix” that:

  • I could change the inner for to for (int j = 1; j < 10; j++) – probably correct.
  • I could add a declaration for j before the inner for loop, or the outer for loop – possibly correct.
  • I could change j to i in the inner for loop – probably wrong!
  • and so on.

The point is that you need to understand what your code is trying to do in order to find the right fix.

Obscure causes

Here are a couple of cases where the “Cannot find symbol” is seemingly inexplicable … until you look closer.

  1. Incorrect dependencies: If you are using an IDE or a build tool that manages the build path and project dependencies, you may have made a mistake with the dependencies; e.g. left out a dependency, or selected the wrong version. If you are using a build tool (Ant, Maven, Gradle, etc), check the project’s build file. If you are using an IDE, check the project’s build path configuration.
  2. Cannot find symbol ‘var’: You are probably trying to compile source code that uses local variable type inference (i.e. a var declaration) with an older compiler or older --source level. The var was introduced in Java 10. Check your JDK version and your build files, and (if this occurs in an IDE), the IDE settings.
  3. You are not recompiling: It sometimes happens that new Java programmers don’t understand how the Java tool chain works, or haven’t implemented a repeatable “build process”; e.g. using an IDE, Ant, Maven, Gradle and so on. In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like …
  4. An earlier build problem: It is possible that an earlier build failed in a way that gave a JAR file with missing classes. Such a failure would typically be noticed if you were using a build tool. However if you are getting JAR files from someone else, you are dependent on them building properly, and noticing errors. If you suspect this, use tar -tvf to list the contents of the suspect JAR file.
  5. IDE issues: People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists … or the reverse situation.
    • This could happen if the IDE has been configured with the wrong JDK version.
    • This could happen if the IDE’s caches get out of sync with the file system. There are IDE specific ways to fix that.
    • This could be an IDE bug. For instance @Joel Costigliola described a scenario where Eclipse did not handle a Maven “test” tree correctly: see this answer. (Apparently that particular bug was been fixed a long time ago.)
  6. Android issues: When you are programming for Android, and you have “Cannot find symbol” errors related to R, be aware that the R symbols are defined by the context.xml file. Check that your context.xml file is correct and in the correct place, and that the corresponding R class file has been generated / compiled. Note that the Java symbols are case sensitive, so the corresponding XML ids are be case sensitive too.Other symbol errors on Android are likely to be due to previously mention reasons; e.g. missing or incorrect dependencies, incorrect package names, method or fields that don’t exist in a particular API version, spelling / typing errors, and so on.
  7. Hiding system classes: I’ve seen cases where the compiler complains that substring is an unknown symbol in something like the followingString s = ... String s1 = s.substring(1); It turned out that the programmer had created their own version of String and that his version of the class didn’t define a substring methods. I’ve seen people do this with SystemScanner and other classes.Lesson: Don’t define your own classes with the same names as common library classes!The problem can also be solved by using the fully qualified names. For example, in the example above, the programmer could have written:java.lang.String s = ... java.lang.String s1 = s.substring(1);
  8. Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. See this page for more information.You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java uxxxx escapes for other characters.

What does a “Cannot find symbol” error mean? Answer #2:

One more example of ‘Variable is out of scope’

As I’ve seen that kind of questions a few times already, maybe one more example to what’s illegal even if it might feel okay.

Consider this code:

if(somethingIsTrue()) {
  String message = "Everything is fine";
} else {
  String message = "We have an error";
}
System.out.println(message);

That’s invalid code. Because neither of the variables named message is visible outside of their respective scope – which would be the surrounding brackets {} in this case.

You might say: “But a variable named message is defined either way – so message is defined after the if“.

But you’d be wrong.

Java has no free() or delete operators, so it has to rely on tracking variable scope to find out when variables are no longer used (together with references to these variables of cause).

It’s especially bad if you thought you did something good. I’ve seen this kind of error after “optimizing” code like this:

if(somethingIsTrue()) {
  String message = "Everything is fine";
  System.out.println(message);
} else {
  String message = "We have an error";
  System.out.println(message);
}

“Oh, there’s duplicated code, let’s pull that common line out” -> and there it it.

The most common way to deal with this kind of scope-trouble would be to pre-assign the else-values to the variable names in the outside scope and then reassign in if:

String message = "We have an error";
if(somethingIsTrue()) {
  message = "Everything is fine";
} 
System.out.println(message);

What does a “Cannot find symbol” error mean? Answer #3:

You’ll also get this error if you forget a new:

String s = String();

versus

String s = new String();

because the call without the new keyword will try and look for a (local) method called String without arguments – and that method signature is likely not defined.

And one of the simplest solution that might work for you in 99% of the cases is:

Using IntelliJ

Select Build->Rebuild Project will solve it.

Hope this post helped you in understanding what does a “Cannot find symbol” error means.

Follow Programming Articles for more!

Intellij дает мне эту ошибку для кода scala:

    Cannot resolve symbol "println"

Настройки проекта:

Проект SDK:

  Intellij IDEA Community Edition IC-141.2735.5(openjdk version "1.8")

Уровень языка проекта:

  8 - Lambdas, type annotations etc. 

Настройки платформы:

SDKs:

   1.8   /usr/lib/jvm/java-8-openjdk-amd64

   IntelliJ IDEA Community Edition IC-141.2735.5

Глобальные библиотеки:

   scala-sdk-2.11.6

РЕДАКТИРОВАТЬ:

Компилятор сообщает, что println имеет несколько реализаций:

    scala-lang:scala-library:2.11.6.jar
    scala-lang:scala-library:2.11.6.jar

Что это значит?

15 окт. 2015, в 19:21

Поделиться

Источник

2 ответа

public class Nurse extends Employee {
    public Nurse(boolean working, long id, String name, String department) {
        super(working, id, name, department);

        // here println can be resolved. Because it inside of a function.
        System.out.println("Invoking constructor "); 
    }

   // System.out.println("Some messge "); // here println can't be resolved.
}

romanlukichev
15 авг. 2016, в 02:48

Поделиться

Я не знаю, насколько это актуально, но у меня была такая же проблема. Для меня это работало, чтобы просто добавить Scala SDK в «Глобальные библиотеки»: удалите его с помощью знака красного минуса, а затем, с значком «зеленый плюс», снова добавьте Scala SDK.

ура

Nico
05 фев. 2016, в 11:31

Поделиться

Ещё вопросы

  • 0angular $ http не отправляет никакого значения на сервер
  • 0Как скрыть таблицу с помощью переключателя, используя Java Script в HTML?
  • 0Функция запуска через некоторое время в jquery и автоматическая нарезка изображений
  • 1Почему постфиксные операторы в Java оцениваются справа налево?
  • 0Rational Software Architect, как читать файлы .h и .cpp в новый проект
  • 0Применение таблицы стилей к одному элементу
  • 0Не работает директива в угловых
  • 0Сравните данные в Angular
  • 1Геолокация для iPhone JavaScript Веб-приложение
  • 1Как уменьшить временную сложность или повысить эффективность программы, находя промежутки месяца, используя питонов
  • 1В pandas / numpy как создать сводную таблицу с количеством строковых элементов?
  • 0Как сосредоточиться на первом поле ввода в диалоговом окне
  • 0Вызов функции Javascript из мобильного тела HTML onorientationchange
  • 1Изменение данных адаптера
  • 0Как отсортировать XML-файлы в PHP
  • 0OpenCart VQMod Недопустимая ошибка регулярного выражения
  • 1Как изменить цвет фона JFrame [дубликата]
  • 0JS Установка атрибута onclick разными способами
  • 0JQuery / JS: активировать два div, при этом деактивируя все остальные при нажатии на один div
  • 1Разве shutil.copyfile не должен заменять ссылку в dst с установленным follow_symlinks?
  • 0Добавление div с load () на иконку для многих братьев и сестер
  • 0По центру выровнять div, который имеет float: left
  • 0Как непрерывно запускать скрипт PHP на сервере виртуального хоста?
  • 0Разница дат только с учетом года, месяца, дня
  • 0Ошибка разбора: синтаксическая ошибка, неожиданное ‘<‘ в C: wamp www jmb_system anggerik include functions.php в строке 7
  • 12 Intent Filters, 1 Activity — Кто это открыл?
  • 1У меня странная проблема с питоном, когда я пытаюсь использовать pycharm
  • 0MySQL удаленное соединение из UWP с ошибкой сокета, но соединение TCP
  • 0AngularJS доступ к свойствам обещанного объекта в функции succes
  • 0директива угловой пагинации не работает
  • 0Флажки UniformJS не работают в Handsontable?
  • 0После символической ссылки: ОШИБКА 2002 (HY000): Не удается подключиться к локальному серверу MySQL через сокет ‘/tmp/mysql.sock’ (2)
  • 1Как десериализовать с помощью XStream?
  • 0Eclipse и Mysql Ошибка подключения
  • 0Проблемы при приготовлении супа: BeautifulSoup не открывает весь источник страницы, останавливаясь на / html
  • 1Как я могу скачать Android 2.0 SDK сейчас
  • 1повторно использовать кэшированные весенние контексты для создания большего контекста
  • 0Обратная косая черта и апостроф не хранятся в MySQL при правильном использовании CodeIgniter
  • 0Создание эффекта калейдоскопа из изображения с использованием opencv
  • 1Что такое эквивалент C # Rawinput в Python?
  • 1Проблема, связанная с жизненным циклом деятельности
  • 1Класс C # Деинициализация динамической памяти
  • 1Как заставить страницу выполнения Windows обновиться, когда она выходит на передний план?
  • 0Диалог JQuery UI отключен в IE10
  • 0AngularJS Formly — повторная валидация секции
  • 1Как использовать комбинацию значений столбцов для фильтрации данных и создания подмножеств?
  • 1Создание макета ListView из ArrayList
  • 0SQL-запрос — фильтр с другим типом
  • 0закрыть скрытый div и кликнуть другой div
  • 0Получение строки запроса в PHP

Сообщество Overcoder

nariku

1 / 1 / 0

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

Сообщений: 20

1

20.10.2009, 13:46. Показов 17281. Ответов 5

Метки нет (Все метки)


Написал прогу

Java
1
2
3
4
5
6
7
8
9
10
11
public class integer
{public static void main(String[]args)
{
MyTerminalIO myterminal=new MyTerminalIO();
 
int x,y;
y=myterminal.getInt("Введите число N суток");
x=1440*y;
myterminal.println("Колличество минут в N сутак = ",x);
}
}

выдает ошибку указывает на точку после myterminal

C:Documents and SettingsвованРабочий столЛЕХА 2integer.java:9: cannot resolve symbol
symbol : method println (java.lang.String,int)
location: class MyTerminalIO
myterminal.println(«Колличество минут в N сутак = «,x);
^
1 error

Tool completed with exit code 1
что здесь не правильно

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



0



Mobile Developer

238 / 234 / 18

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

Сообщений: 917

20.10.2009, 14:07

2

у вас Y не определен…. ой сорри не заметил определен))
мне кажеться что проблема у вас MyTerminalIO.как я понимаю это ваша библиотека вы сами ее написали??



0



1 / 1 / 0

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

Сообщений: 20

20.10.2009, 14:11

 [ТС]

3

я уже сам разобрался всем спасибо



0



0 / 0 / 0

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

Сообщений: 8

20.10.2009, 17:57

4

написал бы в чем ошибка чтобы другие знали.



0



1 / 1 / 0

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

Сообщений: 20

20.10.2009, 18:10

 [ТС]

5

C:Documents and SettingsвованРабочий столЛЕХА 2integer.java:9: cannot resolve symbol
symbol : method println (java.lang.String,int)
location: class MyTerminalIO
myterminal.println(«Колличество минут в N сутак = «,x);
^
правильное написание

C:Documents and SettingsвованРабочий столЛЕХА 2integer.java:9: cannot resolve symbol
symbol : method println (java.lang.String,int)
location: class MyTerminalIO
myterminal.println(«Колличество минут в N сутак = «+x);



1



Mobile Developer

238 / 234 / 18

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

Сообщений: 917

20.10.2009, 21:25

6

Верно я тоже проглядел это=)))синтаксис Си путает))))



0



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

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

  • Cannot resolve method java ошибка
  • Cannot render error page for request
  • Cannot reinitialise datatable for more information about this error
  • Cannot recover from an error please reinstall the application from the support center 8007
  • Cannot recover after last error any further errors will be ignored перевод

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

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