Android应用程序保持随机数相同

时间:2017-02-11 13:22:05

标签: java android if-statement

之前我发布过此代码,但这是一个不同的问题。

当猜测'按下按钮,生成一个随机数。代码的唯一问题是它每次都会生成一个新的数字,无论用户是否猜到了正确的数字。理想情况下,我想给用户一个3猜测限制,这将要求应用程序保持生成的随机数相同,然后在3次错误尝试后重置。因为我很长一段时间没有做过任何java,所以我已经陷入了停滞状态,并且在将它合并到这个应用程序方面让我感到困惑。

提前致谢

package lab.mad.cct.c3375331task1;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import  android.support.v7.app.AlertDialog;
import     android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Random;

public class Task1Activity extends     AppCompatActivity {

    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task1_layout);

        final TextView textResponse = (TextView)               findViewById(R.id.txtResponse);
        final TextView guessText = (TextView)  findViewById(R.id.txtAnswer);
        final EditText userGuess = (EditText) findViewById(R.id.etNumber);

        Button pressMe = (Button) findViewById(R.id.btnGuess);



    // When the button is clicked, it shows the text assigned to the txtResponse TextView box
        pressMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String randText = "";
                Random randGen = new   Random();
                int ranNum = randGen.nextInt(5);
                int userNumber =       Integer.parseInt(userGuess.getText().to String());
                int attempts = 0;


                if (userNumber >19 ) {
                guessText.setText("Please guess between 0 and 20");
                } else if (userNumber == ranNum) {
                    guessText.setText("You got it!");
                } else if (userNumber < ranNum) {
                    guessText.setText("Your answer is too low. Guess     again!");
                  guessText.setBackgroundColor(Color.RED);
                } else if (userNumber > ranNum) {
                    guessText.setText("Your answer is too high.  Guess again!");
                }

                randText = Integer.toString(ranNum);
                textResponse.setText("");

                userGuess.setText("");

            }
        });

    } 



}

2 个答案:

答案 0 :(得分:0)

int userNumber = Integer.parseInt(userGuess.getText().to String());删除onClick(View v),因为每次按下guessme按钮,都会生成新号码。

答案 1 :(得分:0)

在你的班级中声明一些变量

public static final int ATTEMPTS = 3;
public int attempt = 0;
public int currentRandomNumber = new Random().nextInt(5);

在onClick();

if(attempt >= ATTEMPTS){
  attempt = 0;
  currentRandomNumber = new Random().nextInt(5);
} else {
  attempt++;
}

// the rest of your code..

另外,你正在使用rand..nextInt(5),但是根据代码的外观,你应该使用..nextInt(20)