[英]Android App Keeping Random Number the Same
我之前已經發布了此代碼,但這是一個不同的問題。
當按下“猜測”按鈕時,將生成一個隨機數。 該代碼的唯一問題是,無論用戶是否猜測正確的數字,它每次都會生成一個新數字。 理想情況下,我想給用戶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("");
}
});
}
}
刪除int userNumber = Integer.parseInt(userGuess.getText().to String());
來自onClick(View v)
原因,因為每次按下猜測按鈕時,都會生成新的數字。
在類中聲明一些變量
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.