我想比较两组数字。我将在代码中随机生成第一个。第二个将输入EditText。
我希望比较这两个数字,看看它们是否匹配。
随机数:
public static int random() {
if (randomNumberGenerator == null)
initRNG();
return randomNumberGenerator.nextInt();
}
private static Random randomNumberGenerator;
private static synchronized void initRNG() {
if (randomNumberGenerator == null)
randomNumberGenerator = new Random();
}
显示随机选择的数字
display = (TextView) findViewById (R.id.textView1);
display.setText ("Random Number:" + random ());
我如何比较这两个数字?
答案 0 :(得分:1)
您可以使用以下内容:
display = (TextView) findViewById (R.id.textView1);
EditText myEditText = ...; // Find your EditText, maybe by ID?
int random = random(); // Get your random value
display.setText("Random Number:" + random()); // Show the random number
int numberEntered = -1; // Default value for numberEntered; should be a value you wouldn't get randomly
try {
// Here, we try to make a number out of the EditText; if it fails, we get a Toast error
numberEntered = Integer.parseInt(myEditText.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(myEditText.getContext(), "That's not a number!", Toast.LENGTH_LONG).show(); // Tell the user they didn't enter a number
}
if (random == numberEntered) {
// HAPPY DAY, THEY MATCH!
} else {
// No luck :(
}
答案 1 :(得分:-1)
只需在两个数字之间进行减法,如果结果为0,则两个数字都匹配。
编辑:减法只是表明两者都是数字的一种方式。显然,直接比较两个数字而不是减去和比较更有意义。