This question already has answers here:
Closed 2 years ago.
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())++);
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);
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
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?
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.