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

I’ve noticed bizarre behavior with Eclipse version 4.2.1 delivering me this error:

String cannot be resolved to a variable

With this Java code:

if (true)
    String my_variable = "somevalue";
    System.out.println("foobar");

You would think this code is very straight forward, the conditional is true, we set my_variable to somevalue. And it should print foobar. Right?

Wrong, you get the above mentioned compile time error. Eclipse is trying to prevent you from making a mistake by assuming that both statements are within the if statement.

If you put braces around the conditional block like this:

if (true){
    String my_variable = "somevalue"; }
    System.out.println("foobar");

Then it compiles and runs fine. Apparently poorly bracketed conditionals are fair game for generating compile time errors now.

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

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

    }
}

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

I’m a complete beginner to Java, and after learning some of the basics, I decided to do some practice problems. The one I settled on is to create a program that asks for your name, then will only greet you if your name is Alice or Bob. Here’s what I have so far.

I’ve searched for solutions on various forums, but none them seem to be having the same problem. Here is my code:

import java.util.Scanner;

public class codingchallenge {

	public static void main(String[] args) {
		
		System.out.println("Hello, what is your name?");
		Scanner name = new Scanner(System.in);
		System.out.println(name.nextLine());
		name.close();
			if (name == Alice) {
				System.out.println("Hello, Alice");
			}
			
			else if (name == Bob){
				System.out.println("Hello, Bob");
			}
			else {
				System.out.println("Your name isn't Alice or Bob!");
			}
		name.close();
	}
}

And here is was the compiler says:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	Alice cannot be resolved to a variable
	Bob cannot be resolved to a variable

Thanks to everyone who helps out in advance!

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

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;

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

    }
}

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;

}

}

Возможно, вам также будет интересно:

  • Candy сушильная машина ошибка loc
  • Candy сушильная машина ошибка e14
  • Candy стиральные машины ошибка е03 как устранить
  • Candy automatic tempo ошибка e02
  • Candy aquamatic ошибка e02 как исправить

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

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