所以我试图在我的Android游戏中添加生命,当我运行我的if else
块时,生命只会减1或增加1但不会更进一步向下或向上一个,每次猜测错误时我都需要它下降,但事实并非如此。
这是代码块,也许我只需要循环它,但我不确定如何。
int lives = 3;
if(guessNumber.getValue() != number) {
lives--;
Log.d("dicee", "You have " + lives + " lives left");
} else {
lives++;
Log.d("dicee", "You have " + lives + " lives left");
}
如果需要任何其他细节,所有代码都在这里
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.NumberPicker;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button rollButton;
rollButton = (Button) findViewById(R.id.rollButton);
//image views for dice
final ImageView leftDice = (ImageView)
findViewById(R.id.image_leftDice);
//Dice array to grab and display images of dice
final int[] diceArray =
{R.drawable.dice1,
R.drawable.dice2,
R.drawable.dice3,
R.drawable.dice4,
R.drawable.dice5,
R.drawable.dice6};
rollButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("dicee", "Ze Button Has Been Pressed!");
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(7);
Log.d("dicee", "The Random Number Is: " + number);
leftDice.setImageResource(diceArray[number - 1]);
NumberPicker guessNumber = null;
guessNumber = (NumberPicker)findViewById(R.id.guessNumber);
guessNumber.setMaxValue(6);
guessNumber.setMinValue(1);
guessNumber.setWrapSelectorWheel(false);
if(guessNumber.getValue() == number) {
Log.d("dicee", "You Are Correct");
} else {
Log.d("dicee", "Try Again");
}
int lives = 3;
if(guessNumber.getValue() != number) {
lives--;
Log.d("dicee", "You have " + lives + " lives left");
} else {
lives++;
Log.d("dicee", "You have " + lives + " lives left");
}
}
});
}
}
答案 0 :(得分:2)
您在方法中设置int lives = 3;
。因此,每次点击它都是3,你可以向上或向下计数。
您必须在课程外保留lives
。例如,将其放在final Button rollButton;
下面。
答案 1 :(得分:2)
每当用户点击rollButton时,生命将显示为2(如果递减),否则为4(如果递增),这背后的原因是您将实时变量声明并初始化为onClick方法,因此每次用户点击按钮时将显示2或4.
在此问题的解决方案中,声明并初始化方法(On class level)之外的变量。