我已经发布此代码之前,但这是一个不同的问题。Android应用程序保持随机数字相同
当按下'猜测'按钮时,会产生一个随机数。代码的唯一问题就是它每次都会生成一个新号码,而不管用户是否猜对了正确的号码。理想情况下,我想给用户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("");
}
});
}
}
不要选择'新的随机()'在循环内。它每次都将序列重置到同一点。 –