Variable expected

19,831

Solution 1

The ++ operator only makes sense when applied to a declared variable.

This operator will add one to an integer, long, etc. and save the result to the same variable in-place.

If there is no declared variable, there is nowhere to save the result, which is why the compiler complains.

One way to allow use of the ++ operator in this situation would be (not the most concise code, but to illustrate the point):

int myVariable = this.answer.getPoints();
myVariable++;
this.answer.setPoints(myVariable);

Solution 2

this.answer.getPoints() will return a value, and you can't use increment ++ or decrement -- on that. You can only use it on variables.

If you want to add 1 to it, you can do it as:

this.answer.setPoints((this.answer.getPoints())+1);

I know that, but why?

You can do this:

int x = 5;
x++; // x is a variable and can have value 6

but not this:

5++; // 5 is a value and can't have value 6

Solution 3

Change this:

this.answer.setPoints((this.answer.getPoints())++);

to:

this.answer.setPoints((this.answer.getPoints())+1);

++ will increment a variable with 1, but since this.answer.getPoints() will return a value and its not a defined variable, it won't be able to store the incremented value.

Think of it like doing: this.answer.getPoints() = this.answer.getPoints() + 1, where would the incremented value be stored?

Solution 4

The error is just in this bit:

(this.answer.getPoints())++

The first part of this (this.answer.getPoints()) creates an rvalue: effectively, an anonymous variable that lasts almost no time.

The second part ++ increments that anonymous variable after it is passed into setPoints().

Then, the anonymous variable (now incremented) is thrown away.

The compiler/IDE knows that you're doing something that will never be used (incrementing a temporary value), and is flagging it.

Share:
19,831
Andrew Tobilko
Author by

Andrew Tobilko

Updated on August 11, 2022

Comments

  • Andrew Tobilko
    Andrew Tobilko about 1 year
    private void calculateForEachQuestion() {
        ...
        if (questions.size() >= answers.size()) {
            answers.forEach(answer -> {
                if (questions.contains(answer))
                    this.answer.setPoints((this.answer.getPoints())++);
                    // Variable expected  ^                    
        });
    }
    

    The error I encountered is:

    unexpected type
    required: variable
    found: value

    What is wrong with the statement?

    this.answer.setPoints((this.answer.getPoints())++);
    
  • RaminS
    RaminS over 7 years
    Why not omit this? It is totally unnecessary, is it not?
  • Louis Wasserman
    Louis Wasserman over 7 years
    @AndrewTobilko because you can't modify the return value of a method, and ++ modifies the variable it's used on?