亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在點擊監聽器上刷新隨機數?

如何在點擊監聽器上刷新隨機數?

神不在的星期二 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 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號