Accumulated value -java - simple question
one simple question. I need to sum a value, when a condition is verified, so i have this code
private int sum;
private int sum1;
private int sum2;
private int sum3;
public int pontuationOfpl开发者_高级运维ayers() {
if (winner() == 0) {
return sum += 20;
}
else if (winner()==1) {
return sum1 += 20;
}
else if (winner() ==2) {
return sum2 += 20;
}
else
return sum3 += 20;
}
the problem that i have is when the method is called it always start again with 0, so the result must be like, 20, 40, 60, but because of new initialization is always 20.
how can i solve that? like store the value of the variable
thanks!
script:edit
You probably want to make sum a class member, e.g.:
private int sum = 0;
public int pontuationOfplayers() {
if (winner() == 0) {
System.out.println("aqui");
int value0 = 0;
return sum += value0+=20;
}
else {
System.out.println("aquiii");
int value3 = 0;
return sum += value3+=20;
}
}
Based on your update I would suggest doing:
private int sum[] = new int[4];
public int pontuationOfplayers() {
// (assuming winner() returns 3 for the final case)
return sum[winner()] += 20;
}
make sum an instance variable of your class. currently it is a local variable and hence it is initiatilized per method call.
The sum value will need to be created and stored outside this method if it is called several times and you want to maintain the sum. Either store it in a class variable or a local variable in the method that is calling the pontuationOfplayers() method.
Although other answers solve your problem, they don't address what caused it: you are just starting to learn to program.
Read beginner tutorials on Java, Java classes and Java OOP (object-oriented programming). For example, you may start with this question: https://stackoverflow.com/questions/1168919/java-tutorials-for-beginning-programmer
Happy coding!
sum
should be a member of the class and thus defined
private int sum = 0;
within the class(but outside the methods). It is then preserved within the instance of the class, exists for the lifetime of that instance and can be modified by the methods within the class.
What you currently have defined exists only for the lifetime of the method invocation, and will go out of scope as soon as you exit that method.
精彩评论