Reputation: 9
When I execute the code, it always goes to the else condition. But I want the if statement to run when score=true; I cannot figure out how to do this...kindly help me out. If not this way, is there any other way I can approach?
public class withComp extends Activity {
public boolean isPlayer2=false, score=false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.withcomp);
final Button one = (Button)findViewById(R.id.one);
final TextView winner = (TextView)findViewById(R.id.winner);
one.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if(isPlayer2==false)
{
one.setText("X");
score = true;
one.setEnabled(false);
isPlayer2 = true;
}
else
{
one.setText("O");
one.setEnabled(false);
isPlayer2=false;
}
}
});
if(score == true)
{
winner.setText("won");
}
else {
winner.setText("lose");
}
}
}
Upvotes: 0
Views: 168
Reputation: 7383
For example:
public class withComp extends Activity {
public boolean isPlayer2=false, score=false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.withcomp);
final Button one = (Button)findViewById(R.id.one);
final TextView winner = (TextView)findViewById(R.id.winner);
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isPlayer2) {
one.setText("X");
score = true;
one.setEnabled(false);
isPlayer2 = true;
} else {
one.setText("O");
one.setEnabled(false);
isPlayer2=false;
}
// XXX Move it here
if (score) {
winner.setText("won");
} else {
winner.setText("lose");
}
}
});
}
}
Upvotes: 1
Reputation: 8640
a few things,
;
after if statement, and i'm supprised you were able to compiled and execute this codeif-else
block is executed in method create
and you setting value of score
in listener, which means, blockif-else
will be executed after you create your activity, while value score
will be setted to true
after press buttonUpvotes: 0
Reputation: 67
Use it this way"
if(score){
winner.setText("won");
}
else {
winner.setText("lose");
}
Upvotes: 0
Reputation: 69
Just use
if(score)
Without the comma
You don't need to write
if (variable == true)
or if (variable == false)
It's much better just to write
if (variable)
or if (!variable)
Upvotes: 5
Reputation: 1679
Your problem lies in if(score == true);
if clauses do not need a semicolon after the condition, but a statement. Giving it a semicolon passes it the null statement, meaning nothing will happen.
After that it will execute both the blocks following, overwriting what happens in the block you intended to be executed if score is true
.
You can fix this simply by removing the semicolon, letting it correctly execute the block.
Upvotes: 0