我正在尝试更改应用启动时生成的随机数,并要求用户输入新内容?如您所见,当前代码显示如果用户猜出正确的数字,他将不得不再次重启应用程序。而不是这样做,我想在客户正确的时候继续改变随机数。
public class MainActivity extends Activity {
int randomNumber;
int number;
public void randomNumberGenerator (View view){
EditText userInput = (EditText)findViewById(R.id.userRandomText);
do {
number = Integer.parseInt(userInput.getText().toString());
if (number == randomNumber) {
Toast.makeText(getApplicationContext(), "Your number " + number + "is equal to generated number. CONGRATULATION !! Try Again: ", Toast.LENGTH_SHORT).show();
} else if (number < randomNumber) {
Toast.makeText(getApplicationContext(), "Your number " + number + "is lower than generated random number", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Your number " + number + "is greater than generated random number", Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_udemy);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
Random randomGenerator = new Random();
randomNumber = randomGenerator.nextInt(20);
System.out.print(randomNumber);
答案 0 :(得分:2)
将这些行移至generateRandomNumber
Random randomGenerator = new Random();
randomNumber = randomGenerator.nextInt(20);
System.out.print(randomNumber);
然后你可以在用户猜对了
时再添加一次randomNumber = randomGenerator.nextInt(20);
所以你的代码看起来像这样
Random randomGenerator = new Random();
randomNumber = randomGenerator.nextInt(20);
System.out.print(randomNumber);
do {
number = Integer.parseInt(userInput.getText().toString());
if (number == randomNumber) {
Toast.makeText(getApplicationContext(), "Your number " + number + "is equal to generated number. CONGRATULATION !! Try Again: ", Toast.LENGTH_SHORT).show();
randomNumber = randomGenerator.nextInt(20);
} else if (number < randomNumber) {
Toast.makeText(getApplicationContext(), "Your number " + number + "is lower than generated random number", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Your number " + number + "is greater than generated random number", Toast.LENGTH_SHORT).show();
}
}