该程序应使用预设的问题和答案,并检查是否按下了是或否按钮。它有一个主要的活动文件和一个称为Question的类文件,但是运行时,输出显示“错误:从内部类内部访问局部变量问题;需要声明为final”。我修理它?谢谢,在数组列表声明前添加final关键字无效。
public class MainActivity extends Activity {
private TextView display_question;
private TextView display_result;
private static int rand_int;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random random = new Random();
display_question = findViewById(R.id.txt_question);
display_result = findViewById(R.id.txt_result);
ArrayList<Question> questions; //in class method
questions = Question.getQuestions(); //in class method, arraylist
rand_int = random.nextInt(4);
display_question.setText(questions.get(rand_int).getQuestion());// where i is an integer
Button btn_true = findViewById(R.id.btn_true);
btn_true.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean input = true;
String output = "correct answer";
String output2 = "incorrect answer";
if (questions.get(rand_int).isAnswer()==input){
display_result.setText(output);
}
else {
display_result.setText(output2);
}
}
});
Button btn_false = findViewById(R.id.btn_false);
btn_false.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean input = false;
String output = "correct answer";
String output2 = "incorrect answer";
if (questions.get(rand_int).isAnswer()==input){
display_result.setText(output);
}
else {
display_result.setText(output2);
}
}
});
Button btn_next = findViewById(R.id.btn_next);
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rand_int = random.nextInt(4);
display_question.setText(questions.get(rand_int).getQuestion());// where i is an integer
}
});
}
}
问题课:
import java.util.ArrayList;
public class Question {
private String question;
private boolean answer;
private Question(String question, boolean answer) {
this.question = question;
this.answer = answer;
}
public String getQuestion() {
return question;
}
public boolean isAnswer() {
return answer;
}
public static ArrayList<Question> getQuestions(){
ArrayList<Question> questions = new ArrayList<>();
questions.add(new Question("B", false));
questions.add(new Question("A", true));
questions.add(new Question("c", false));
questions.add(new Question("d", false));
questions.add(new Question("e", true));
return questions;
}
}