Cannot be resolved to a variable ошибка

How to fix cannot be resolved to a variable in Java.
Fix Java Cannot Be Resolved to a Variable Error

This guide will teach you how to fix the cannot be resolved to a variable error in Java.

For this, you need to understand the scope of a programming language. Keep reading this compact guide to learn more and get your fix to this error.

Fix the cannot be resolved to a variable Error in Java

In Java programming language, we use curly brackets {} to identify the scope of a class, functions, and different methods.

For instance, take a look at the following code:

public static void calculateSquareArea(int x)
{
    System.out.println(x*x);
}

In the above code example, the scope of the variable x is limited within the curly brackets {}. You cannot call or use it outside this scope. If you try, the cannot be resolved to a variable error will come out.

It means it cannot detect the initialization of variables within its scope. Similarly, if you make a private variable, you cannot call it inside a constructor.

Its scope is out of bounds. Here’s the self-explanatory code.

public class Main 
{
    public static void main(String args[]) 
    {
        int var  =3;  
        // scope is limited within main Block;
        // The Scope of var Amount Is Limited..........
        // Accessible only Within this block............
    }
    public static void Calculate (int amount)
    {
      // The Scope of Variable Amount Is Limited..........
      // Accessible only Within this block............
    }
}

the compiler says

Exception in thread «main» java.lang.Error: Unresolved compilation problems:

i cannot be resolved to a variable

i cannot be resolved to a variable

i cannot be resolved to a variable

i cannot be resolved to a variable

i cannot be resolved to a variable

at minimusikplayer2.MiniMusikPlayer2.los(MiniMusikPlayer2.java:25)

at minimusikplayer2.MiniMusikPlayer2.main(MiniMusikPlayer2.java:9)

I will be thankfull for any support. Now I have to go but I will be back in 5 hours!!!

The problems are in line 25,26 and 27

package minimusikplayer2;

import javax.sound.midi.*;

public class MiniMusikPlayer2 implements ControllerEventListener {

public static void main(String[] args) {

MiniMusikPlayer2 mini = new MiniMusikPlayer2();

mini.los();

}

public void los() {

try {

Sequencer sequencer = MidiSystem.getSequencer();

sequencer.open();

int[] gewuenschteEvents = {127

};

sequencer.addControllerEventListener(this, gewuenschteEvents);

Sequence seq = new Sequence(Sequence.PPQ, 4);

Track track = seq.createTrack();

for (int i = 5; i < 60; i+= 4); {

track.add(eventErzeugen(144,1,i,100,i));

track.add(eventErzeugen(176,1,127,0,i));

track.add(eventErzeugen(128,1,i,100,i + 2));

}

sequencer.setSequence(seq);

sequencer.setTempoInBPM(220);

sequencer.start();

Thread.sleep(5000);

sequencer.close();

}catch (Exception ex) {ex.printStackTrace();}

}

public void controlChange(ShortMessage event) {

System.out.println(«la»);

}

public MidiEvent eventErzeugen(int comd, int chan, int one, int two, int tick){

MidiEvent event = null;

try{

ShortMessage a = new ShortMessage();

a.setMessage(comd,chan,one,two);

event = new MidiEvent(a, tick);

}catch (Exception e){}

return event;

}

}

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Shane McC

Hi Everyone,

I’m getting this weird error and eclipse is telling me my finalAmount variable can’t be resolved. From looking at it I know it’s outside of the scoop of the for statement and everytime I create a local variable and assign a value to it (it’s zero) my program gets messed up.

My question is, how would I declare the finalAmount variable locally?

Thanks

import java.util.Scanner;

public class CompoundInterest {
    public static void main(String[] args){

        double rate;
        double amount;
        double year;

        System.out.println("This program, with user input, computes interest.n" +
                "It allows for multiple computations.n" +
                "User will input initial cost, interest rate and number of years.");

        Scanner input = new Scanner(System.in);

        System.out.println("What is the inital cost?");
        amount = input.nextDouble();

        System.out.println("What is the interest rate?");
        rate = input.nextDouble();
        rate = rate/100;

        System.out.println("How many years?");
        year = input.nextDouble();

        for(int x = 1; x < year; x++){
            double finalAmount = amount * Math.pow(1.0 + rate, year); 
// the below works but the problem is, it prints the statement out many times. I don't want that.
            /* System.out.println("For " + year + " years an initial " + amount + 
                    " cost compounded at a rate of " + rate + " will grow to " + finalAmount); */
        }


        System.out.println("For " + year + " years an initial " + amount + 
                " cost compounded at a rate of " + rate + " will grow to " + finalAmount);

    }



}

1 Answer

omars

omars

January 3, 2014 4:10am

Shane,

Q: «eclipse is telling me my finalAmount variable can’t be resolved»
A: This is because you are declaring ‘finalAmount’ within the for loop. Once your for loop exits, ‘finalAmount’ goes out of scope. Meaning, Java has no clue it ever existed.

Q: «My question is, how would I declare the finalAmount variable locally?»
A: From what I know, you cannot declare a variable within a loop of any kind if you want to retain the previous value. When you declare a variable within a loop this is what happens:

  1. Your loop begins with an initial value of 0. (This is before the calculation takes place, double finalAmount;)
  2. A value is calculated and assigned to finalAmount.
  3. Your loop ends.
  4. If you loop condition is still valid (x < year), repeat from step one (finalAmount is redeclared and initialized).

Someone please correct me if I said anything wrong about the above steps.

Here is my suggested change to your code, I hope this helps.

import java.util.Scanner;

public class CompoundInterest {
    public static void main(String[] args){

        double rate;
        double amount;
        double year;

        System.out.println("This program, with user input, computes interest.n" +
                "It allows for multiple computations.n" +
                "User will input initial cost, interest rate and number of years.");

        Scanner input = new Scanner(System.in);

        System.out.println("What is the inital cost?");
        amount = input.nextDouble();

        System.out.println("What is the interest rate?");
        rate = input.nextDouble();
        rate = rate/100;

        System.out.println("How many years?");
        year = input.nextDouble();

        /* Calculate the interest over a number of 'years' and 
           assign the value to 'finalAMount'
        */
        double finalAmount = 0;  // Perfectly legal to do this since finalAmount isn't used prior to this.
        for(int x = 1; x < year; x++){
            finalAmount = amount * Math.pow(1.0 + rate, year); 
        }


        System.out.println("For " + year + " years an initial " + amount + 
                " cost compounded at a rate of " + rate + " will grow to " + finalAmount);

    }
}

Did you know that in Java’s standard library, there are a total of more than 500 different exceptions! There lots of ways for programmers to make mistakes — each of them unique and complex. Luckily we’ve taken the time to unwrap the meaning behind many of these errors, so you can spend less time debugging and more time coding. To begin with, let’s have a look at the syntax errors!

Syntax Errors

If you just started programming in Java, then syntax errors are the first problems you’ll meet! You can think of syntax as grammer in English. No joke, syntax errors might look minimal or simple to bust, but you need a lot of practice and consistency to learn to write error-free code. It doesn’t require a lot of math to fix these, syntax just defines the language rules. For further pertinent information, you may refer to java syntax articles.

Working with semicolons (;)

Think of semi-colons (;) in Java as you think of a full-stop (.) in English. A full stop tells readers the message a sentence is trying to convey is over. A semi-colon in code indicates the instruction for that line is over. Forgetting to add semi-colons (;) at the end of code is a common mistake beginners make. Let’s look at a basic example.

This snippet will produce the following error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:  
Syntax error, insert ";" to complete BlockStatements  

at topJavaErrors.JavaErrors.main(JavaErrors.java:3)

You can resolve this error by adding a ; at the end of line 3.

String x = "A";

Braces or parentheses [(), {}]

Initially, it can be hard keeping a track of the starting / closing parenthesis or braces. Luckily IDEs are here to help. IDE stands for integrated development environment, and it’s a place you can write and run code. Replit for example, is an IDE. Most IDEs have IntelliSense, which is auto-complete for programmers, and will add closing brackets and parentheses for you. Despite the assistance, mistakes happen. Here’s a quick example of how you can put an extra closing bracket or miss the ending brace to mess up your code.

If you try to execute this, you’ll get the following error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem:  
Syntax error on token ")", delete this token  
at topJavaErrors.SyntaxErrors.main(SyntaxErrors.java:11)

You can resolve this exception by removing the extra ) on line 9.

Output

My full name is: Justin Delaware

Double Quotes or Quotation Marks (“ ”)

Another pit fall is forgetting quotation marks not escaping them propperly. The IntelliSense can rescue you if you forget the remaining double quotes. If you try including quotation marks inside strings, Java will get confused. Strings are indicated using quotation marks, so having quotation marks in a string will make Java think the string ended early. To fix this, add a backslash () before quotation marks in strings. The backslash tells Java that this string should not be included in the syntax.

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problems:  
Syntax error on token "Java", instanceof expected  
The preview feature Instanceof Pattern is only available with source level 13 and above  
is cannot be resolved to a type  
Syntax error, insert ")" to complete MethodInvocation  
Syntax error, insert ";" to complete Statement  
The method favourtie(String) is undefined for the type SyntaxErrors  
Syntax error on token "language", ( expected  

at topJavaErrors.SyntaxErrors.main(SyntaxErrors.java:5)

In order for you avoid such exceptions, you can add backslahes to the quotes in the string on line 4.

Output

What did Justin say?  
Justin said, "Java is my favourite language"

Here’s your required output, nicely put with double quotes! :)

Other Miscellaneous Errors

Accessing the “Un-Initialized” Variables

If you’re learning Java and have experience with other programming languages (like C++) then you might have a habit of using un-initialized variables (esp integers). Un-initialized variables are declared variables without a value. Java regulates this and doesn’t allow using a variable that has not been initialized yet.

If you attempt to access an uninitialized variable then you’ll get the following exception.

Exception in thread "main" java.lang.Error: Unresolved compilation problem:  
The local variable contactNumber may not have been initialized  
at topJavaErrors.UninitialziedVars.main(UninitialziedVars.java:5)

You can initialize the variable “contactNumber” to resolve this exception.

int contactNumber = 9935856;

Accessing the “Out of Scope” Variables

If you define a variable in a certain method you’re only allowed to access that in the defined scope of it. Like each state has their legitimate currency, and that cannot be used in another state. You cannot use GBP in place of USD in America. Similarly, a variable defined in one method has restricted scope to it. You cannot access a local variable defined in some function in the main method. For further detailed illustration let’s look at an example.

Output

As soon as you run this snippet, you’ll get the exception

Exception in thread "main" java.lang.Error: Unresolved compilation problem:  
country cannot be resolved to a variable  

at topJavaErrors.OutOfScopeVars.main(OutOfScopeVars.java:9)

You can not access the variable “country” outside the method getPersonalDetails since its scope is local.

Modifying the “CONSTANT” Values

Java and other programming languages don’t allow you to update or modify constant variables. You can use the keyword “final” before a variable to make it constant in Java. Apart from that, it’s a convention to write a constant in ALL CAPS for distinction purposes, As a constant resource is often used cross methods across a program.

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem:  
The final field ConstVals.SSN cannot be assigned  
at topJavaErrors.ConstVals.main(ConstVals.java:5)

Remove line 4 for the perfectly functional code.

Misinterpretted Use of Operators ( == vs .equals())

A lot of beginners start working with integers while learning the basics of a programming language. So it can be a challenge to remember that for string comparisons we use the “.equals()” method provided by Java and not == operator like in integers.

Output

It's not a Wednesday!  
It's a Wednesday!

The output is contradictory because “today” and “thirdWeekDay” are referred to 2 different objects in the memory. However, the method “.equals()” compares the content stored in both arrays and returns true if it’s equal, false otherwise.

Accessing a non-static resource from a static method

If you want to access a non-static variable from a static method [let’s say the main method] then you need to create an instance of that object first. But if you fail to do that, java will get angry.

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem:  
Cannot make a static reference to the non-static field postalCode  

at topJavaErrors.NonStaticAccess.main(NonStaticAccess.java:17)

You can fix it, just by replacing line 9.

// Accessing the non-static member variable

// by creating an instance of the object  
System.out.println("What's the postal code of your area? " + address.postalCode);

Conclusion

Programming errors are a part of the learning curve. Frequent errors might slow you down. But as a new programmer, it’s okay to learn things slowly. Now you’re familiar with some of the most common issues. Make sure you practise enough to get ahead of them. Happy coding and keep practising! :)

Seeing “R cannot be resolved to a variable,” is one of the most annoying and recurring problems when developing in Android. Below are the problems I’ve run into and their solutions.

No problems; everything in working order:

HoverDroids-Android-R-Cannot-Be-Resolved-Eclipse-1

Let’s start with a working project (picture above). Notice the following:

  • src/package name is com.example.project
  • gen/package name is EXACTLY the same
  • MainActivity is in src/com.example.project
  • While src and gen are different folders, they have the same packages and any files within the same package can see any other file in that package without having to import the class. Consequently, MainActivity can automatically see R.java and can therefor call R.id.container without errors.

Problem 1: Bad path single package

HoverDroids-Android-R-Cannot-Be-Resolved-Eclipse-2

The image above shows the result of a bad path from MainActivity to R.java. Notice the following:

  • red x on Project Folder, src folder, com.app.project package, and MainActivity.java in the package explorer on the left
  • no red x on any folders or files in the gen folder.
  • Clearly this means the root of the problem is in MainActivity and not with R.java
  • Looking at MainActivity on right side, the R. is underlined in red for any reference to R.java (e.g. R.layout.activity_main and R.id.container)
  • MainActivity is in com.app.project package while R.java is in com.example package, so it cannot automatically see R.java. Since it cannot automatically see R.java it must provide the path to R.java but hasn’t done so using import.

Solution 1:

The first solution is to rename one of the packages to that of the other. When I run into this problem it’s because I renamed my main package and forgot to rename the package in /gen. So, rename /gen/com.example.project by opening the manifest file as shown below. This should automatically rename the package in the package explorer. If it doesn’t, just delete the entire /gen folder and let android recreate it.

HoverDroids-Android-R-Cannot-Be-Resolved-Eclipse-3

Solution 2:

When you don’t want to rename the package in /gen (Problem 2 is a good example), then it’s required that MainActivity has the following line: import com.example.project.R;

HoverDroids-Android-R-Cannot-Be-Resolved-Eclipse-4

Problem 2: Bad path multi-package

HoverDroids-Android-R-Cannot-Be-Resolved-Eclipse-5

The image above shows the result of a bad path from SecondaryActivity to R.java even though MainActivity isn’t experiencing the same problem. Notice the following:

  • red x on Project Folder, src folder, com.app.project.secondaryActivity package, and SecondaryActivity.java in the package explorer on the left
  • no red x on any folders or files in the gen folder.
  • Clearly this means the root of the problem is in SecondaryActivity and not with R.java
  • Looking at SecondaryActivity on right side, the R. is underlined in red for any reference to R.java (e.g. R.layout.activity_main and R.id.container)
  • SecondaryActivity is in com.app.project.secondaryActivity package while MainActivity and R.java are in com.app.project package, so it cannot automatically see R.java. Since it cannot automatically see R.java it must provide the path to R.java but hasn’t done so using import.

Solution:

Use Solution 2 from Problem 1.

Problem 3: Wrong path specified… android.R

HoverDroids-Android-R-Cannot-Be-Resolved-Eclipse-6

The image above shows the result of android.R being imported rather than com.app.project.R Notice the following:

  • red x on Project Folder, src folder, com.app.project package, and in the package explorer on the left
  • no red x on any folders or files in the gen folder.
  • Clearly this means the root of the problem is in MainActivity and not with R.java
  • Looking at MainActivity on right side, the R. is NOT underlined while activity_main and container are
  • MainActivity is in com.app.project package and so is R.java, so no need to import anything since MainActivity can already see R.java
  • Problem is that the code thinks R.layout.activity_main and R.id.container should be in android.R and not com.app.R because of import android.R

Solution:

Delete import android.R

Note: When using auto-complete (e.g. hitting spacebar during R.layout.cont to get R.layout.container), unexpected suggestions appear. This is a result of importing android.R so delete it and the correct suggestions should appear again.

Problem 4: No R.java doesn’t exist after cleaning

First ensure that the problem isn’t a path issue as described above. If all paths are correct then try to select Project Tab->Clean ->Name of project.

If /Gen/com.app.project/R.java does not immediately reappear then an xml file or manifest file have an error – even if Eclipse doesn’t show it! So, go through recently changed files and make sure everything stacks up. Here are some common problems:

  • Didn’t close a view. Every view needs to start and close. For example or
  • Missing quotes. Very common the second quote gets deleted and results in something like
  • Bad drawable names or xml file names. Both MUST be lowercase, number, and no symbols except underscore

Problem 5: R.java shows after cleaning but won’t update

Again, ensure there isn’t a path problem. Then, if a clean regenerates R.java but won’t update it. Very likely the name of a value or enum is not allowed and must be fixed. Look at the R.java file and see what fields have errors and look for un-allowed characters. For example, maybe there is a dash instead of an underscore.

Conclusion

Well, that’s the end of my experience with this problem. Hopefully one of these solutions helped. Let me know if you’ve seen another case and have a solution.

эту переменную определяют после

long n12 = (int) (upc%10);
upc /= 10;
long n11 = (int) (upc%10);
upc /= 10;
long n10 = (int) (upc%10);
upc /= 10;
long n9 = (int) (upc%10);
upc /= 10;
long n8 = (int) (upc%10);
upc /= 10;
long n7 = (int) (upc%10);
upc /= 10;
long n6 = (int) (upc%10);
upc /= 10;
long n5 = (int) (upc%10);
upc /= 10;
long n4 = (int) (upc%10);
upc /= 10;
long n3 = (int) (upc%10);
upc /= 10;
long n2 = (int) (upc%10);
upc /= 10;
long n1 = (int) (upc%10);



int m = (n2 + n4 + n6 + n8 + n10);
long n = (n1 + n3 + n5 + n7 + n9 + n11);
long r = (10-(m+3*n)%10);

вы используете эту переменную, которая не была определена, и после использования вы определяете эти переменные

Изменить: если

Когда вы определяете свой метод с возвращаемым значением в течение длительного времени и возвращаете значение String, см. Возвращаемое значение

return (upc + " is a feasible UPC code"); 

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

public long getUpc(){
  // and return will work
  return (upc + " is a feasible UPC code"); 
}

но если вы хотите использовать только числовое значение, не меняйте его подпись метода, просто верните upc, как это

return upc;

Понравилась статья? Поделить с друзьями:
  • Cannot assign without a target object ошибка
  • Cannot assign to function call ошибка
  • Cannot assign to function call как исправить
  • Cannot allocate initrd error
  • Cannot add or update a child row a foreign key constraint fails как исправить