所以我试图在我的android游戏中添加lives,当我运行我的if elseblock时,lives只会减少1或增加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");
            }
        }
    });
  }

}

最佳答案

每当用户单击rollbutton lives时,将显示为2(如果递减)或4(如果递增),其背后的原因是您在on click方法中声明并初始化live变量,因此每次用户单击button lives时都将显示2或4。
为了解决这个问题,声明并初始化方法之外的变量(在类级别)。

09-28 04:08