问题
I'm fairly new to java, so I don't understand why i'm getting an initialization error. In the code my integer "Memes" is saying that it might not have been initialized and that a local variable hides in field.
private void totalUpdate(int yes){
if (yes==1){
int CompBot = Integer.parseInt(lblbotComp.getText());
int CompTop = Integer.parseInt(lbltopComp.getText());
int CompMid = Integer.parseInt(lblmidComp.getText());
int Memes = Memes + CompBot + CompTop + CompMid;
lbltotalComp.setText("Computer has earned "+ Memes +" points in total");
}
}
private void pointUpdate(int points){
pointsUser = pointsUser + points ;
lbluserPointsEst.setText (""+pointsUser+"");
}
private void computerPointUpdate(int pointComp){
pointsComputer = pointsComputer + pointComp ;
lblcompPointsEst.setText (""+pointsComputer+"");
}
private int play(int points){
int score;
int randomScore = (int)((100 -1 +1)*Math.random() +1);
if (randomScore < points){
score = points;
}
else{
score = 100;
}
return score;
}
private int playComp(int pointsComp){
int score;
int randomScore = (int)((100 -1 +1)*Math.random() +1);
if (randomScore < pointsComp){
score = pointsComp;
}
else{
score = 100;
}
return score;
}
private int Memes = 0;
private final Timer messageTimer;
private int pointsComputer = 0;
private int pointsUser = 0;
private int count;
回答1:
You receive this warning because you have private int Memes
in your class definition, as well as a declared variable int Memes
in totalUpdate()
.
How to fix it depends on what you want:
If you want totalUpdate()
to update the value of Memes
in your object, leave out int
in the line in question like this:
Memes = Memes + CompBot + CompTop + CompMid;
If you want to declare a new local variable, it is better to give it a different name:
int localMemes = Memes + CompBot + CompTop + CompMid;
回答2:
When you do this
int Memes = Memes + CompBot + CompTop + CompMid;
Java treats this as a declaration of a new variable, which hides field
private int Memes = 0;
It looks like you wanted to initialize Memes
which is the field. In order to do that, drop int
in front of the assignment:
Memes = Memes + CompBot + CompTop + CompMid;
回答3:
Probably in this line:
int Memes = Memes + CompBot + CompTop + CompMid;
The variable "Memes" can be either the one defined in the method totalUpdate() or the object's attribute. So the parser gets confused.
Try to change the variable's name to something like localMemes or such.
Also since you're new in Java I suggest reading this article on Naming Conventions: http://www.oracle.com/technetwork/java/codeconventions-135099.html
回答4:
Declare "Memes" at the field level:
int Memes = 0; //for example
then
Memes += CompBot + CompTop + CompMid;
also lower case names for ints/objects helps readability from class names.
memes += compBot + compTop + compMid;
来源:https://stackoverflow.com/questions/37800683/variable-not-initialized-and-hides-in-field