为了账号安全,请及时绑定邮箱和手机立即绑定

如何在点击监听器上刷新随机数?

如何在点击监听器上刷新随机数?

神不在的星期二 2022-05-25 16:01:54
我设法创建了一个简单的猜谜游戏(这很好用),唯一的问题是我似乎无法刷新我一开始生成的随机数。(当他们猜对了数字时)import java.util.Random;public class MainActivity extends AppCompatActivity {private TextView hint;private Button enterGuess;private EditText chosenNumber;Random rand = new Random();int secretNumber = rand.nextInt(99) + 1;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    enterGuess = findViewById(R.id.buttonEnter);    chosenNumber = findViewById(R.id.etEnterNumber);    hint = findViewById(R.id.tvHint);    final String hintHigh = "Guess Higher";    final String hintLow = "Guess Lower";    final String correctGuess = "Correct! Guess the new number!";    enterGuess.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View v) {            int number = Integer.parseInt(chosenNumber.getText().toString());            if (number < secretNumber){                hint.setText(hintHigh);            }            else if (number > secretNumber) {                hint.setText(hintLow);            }            else {                hint.setText(correctGuess);                Random rand = new Random();                int secretNumber = rand.nextInt(99) + 1;            }        }    });}}
查看完整描述

2 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

您应该更新您的实例变量 secretNumber,因此在您的 onClick() 方法中:

this.secretNumber = rand.nextInt(99) + 1;


查看完整回答
反对 回复 2022-05-25
?
慕标5832272

TA贡献1966条经验 获得超4个赞

不要在每次希望重新启动游戏时都创建新的 Random 实例。只需在您已有的实例上调用 nextInt(99) 即可。



查看完整回答
反对 回复 2022-05-25
  • 2 回答
  • 0 关注
  • 148 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号