[英]How do i make a button take text from an edittext and compare it to a random number?
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 . 因为generatePassword始终为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. 上面的代码将始终生成小于1的数字。您应该将其更改为任何其他数字。 Suppose you write
random.nextInt(5);
假设您编写
random.nextInt(5);
Then above line will generate number between 0 to 5 means it can be 0,1,2,3,4. 然后上面的行将生成介于0到5之间的数字,表示它可以是0、1、2、3、4。
Check this link https://www.geeksforgeeks.org/java-util-random-nextint-java/ 检查此链接https://www.geeksforgeeks.org/java-util-random-nextint-java/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.