I'm trying to make my button compare the number in the edit text to the random number I'm generating and make a toast if they're the same. the code runs but no matter what i set the bound to the number in the edit text never equals the random number. Here is my code
Button submit;
EditText etcode;
Random random = new Random();
String generatedPassword = String.format(String.valueOf(random.nextInt(1)));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
mFlower = findViewById(R.id.ivImage);
mDescription = findViewById(R.id.tvDescription);
submit = (Button) findViewById(R.id.btn_submit);
etcode = findViewById(R.id.et_code);
Bundle mBundle = getIntent().getExtras();
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (etcode.getText().toString().equals(generatedPassword)){
Toast.makeText(getApplicationContext(), "CONGRATS", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "TRY AGAIN", Toast.LENGTH_SHORT).show();
}
}
});
Change this line
String generatedPassword = String.format(String.valueOf(random.nextInt(1)));
Because generatePassword is always 0 . That's why it works with zero.
random.nextInt(1);
Above code will always generate number less than 1. You should change it to any other number. Suppose you write random.nextInt(5);
Then above line will generate number between 0 to 5 means it can be 0,1,2,3,4.
Check this link https://www.geeksforgeeks.org/java-util-random-nextint-java/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.