将变量传递给其他方法

时间:2015-06-27 12:29:06

标签: android

我有一个方法,启动if语句onClick以显示列表数组中的问题,删除该项,然后增加一个int,以便再次显示另一个问题onClick。变量在onCreate之前定义。当我第一次从阵列中拉出一个随机项并显示时单击该按钮。如果我再次点击它它什么都不做。什么?

爪哇

public class Careunderfirequiz extends AppCompatActivity{

int questionsAnswered = 0;

List<String> questions = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.myLayout);
    questions.add("1");
    questions.add("2");
    questions.add("3");
    questions.add("4");
    questions.add("5");
    questions.add("6");
    questions.add("7");
    questions.add("8");
    questions.add("9");
    questions.add("10");
}

public void nextQuestion(View view){
    TextView questionsTextView = (TextView)findViewById(R.id.questions);
    Button next = (Button)findViewById(R.id.next);
    if(questionsAnswered == 0){
        Random randomGenerator = new Random();
        String randQuestion = questions.get(randomGenerator.nextInt(questions.size()));
        questionsTextView.setText(randQuestion);
        questions.remove(randQuestion);
        questionsAnswered++;
    }
    if(questionsAnswered == 1){
        Random randomGenerator = new Random();
        String randQuestion = questions.get(randomGenerator.nextInt(questions.size()));
        questionsTextView.setText(randQuestion);
        questions.remove(randQuestion);
        questionsAnswered++;
    }

}

}

1 个答案:

答案 0 :(得分:0)

您使用remove方法输入了String,如果Random类选择了例如值= 2两次,那么这将使用值而不是索引删除项目,第一次{ {1}}方法会删除remove项,但第二次value =2方法不执行任何操作,因为已删除包含remove的项目。

请修正value=2方法

nextQuestion