2 回答
TA贡献1735条经验 获得超5个赞
使 value1 和 value2 成为全局值,并仅在将其与旧值进行比较后才重置这些值。也做了一些其他的重新安排。
这可能是您的代码:
public class MainActivity extends AppCompatActivity {
Random r = new Random();
int points1 = 0;
int value1, value2;
TextView Number1;
TextView Number2;
TextView Answer;
TextView displayPoints;
EditText Attempt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Number1 = findViewById(R.id.number1);
Number2 = findViewById(R.id.number2);
Answer = findViewById(R.id.Answer);
displayPoints = findViewById(R.id.points);
Attempt = findViewById(R.id.Attempt);
value1 = r.nextInt(12 - 1) + 1; //1st randomized set of values
value2 = r.nextInt(12 - 1) + 1; // ^
Number1.setText("" + value1); //assigns randomized values to textEdits
Number2.setText("" + value2); // ^^
}
public void onSubmitCheck(View view) {
reset(); //When button Submit is clicked
} //^ ^ Issue starts here when we click "submit" - the code generates new random values before checking the old ones against the mathematical expression in line 50..
//..meaning the user is already answering to the SECOND question before even attempting the first one.
public void reset() {
int userAnswer = Integer.parseInt(Attempt.getText().toString()); //compares inputted value to an answer from line 50
if (userAnswer == value1 + value2) { //LINE 50
Answer.setText("Correct!");
point();
displayPoints.setText("" + points1);
} else {
Answer.setText("Wrong :( Answer was: " + (value1 + value2));
}
value1 = r.nextInt(12 - 1) + 1; //Assigns 2nd randomized values
value2 = r.nextInt(12 - 1) + 1; // ^
Number1.setText("" + value1);
Number2.setText("" + value2);
TA贡献1801条经验 获得超8个赞
static int points1 = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView Number1 = findViewById(R.id.number1);
TextView Number2 = findViewById(R.id.number2);
TextView Answer = findViewById(R.id.Answer);
EditText Attempt = findViewById(R.id.Attempt);
TextView displayPoints = findViewById(R.id.points);
generateNumbers();
}
public void onSubmitCheck (View view) {
checkResult();
Attempt.clear();
}
private void generateNumbers () {
Random r = new Random();
value1 = r.nextInt(12 - 1) + 1;
value2 = r.nextInt(12 - 1) + 1;
Number1.setText(""+value1);
Number2.setText(""+value2);
}
void checkResult() {
int userAnswer = Integer.parseInt(Attempt.getText().toString());
if (userAnswer == value1 + value2) {
Answer.setText("Correct!");
points1++;
displayPoints.setText(""+ points1);
} else {
Answer.setText("Wrong :( Answer was: " + (value1 + value2));
}
}
试试这个,从一开始这段代码就可以工作。如果您使用另一个名为Next 的按钮来生成下一个 Value ,这将是一个更好的选择。它可以帮助您理解代码。
添加回答
举报