我使用两个按钮在包含 12 个月的数组列表中来回迭代,当我到达最后一个元素并按 prevButton 时,应用程序崩溃,当我返回第一个元素并点击nextButton,我该如何修复我的 if 语句?
我尝试使用 >= 和 <= 来实现,但没有成功
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (i < months.size()) {
Month month = months.get(i);
monthTextView.setText("" + month);
i++;
}
}
});
prevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (i >= 0) {
Month month = months.get(i);
monthTextView.setText("" + month);
i--;
}
}
});
最佳答案
最后一次单击您将更改 i
无论如何值(value)-1
或months.size()
通过添加/减去 1
访问最后/第一个元素后
让我们仔细看看这个 fragment :
if (i >= 0) { // let us assume that i = 0, we are getting inside
Month month = months.get(i); // you are assigning first element of months, everything is fine
monthTextView.setText("" + month); // some data operation - irrelevant
i--; // anyway you are updating i to [i = -1]
}
// one "next" click later...
if (i < months.size()) { // condition is fine because i = -1
Month month = months.get(i); // oooops tried to access months[-1] - ERROR
monthTextView.setText("" + month);
i++;
}
第二种情况也发生了同样的情况
你应该做什么 - 你应该更新 i
仅当当前值强时才值 > 0
或< month.size() - 1
if (i >= 0) {
Month month = months.get(i);
monthTextView.setText("" + month);
i = (i > 0) ? (i - 1) : 0; // for example like this
}
关于java - 如何修复此数组列表的迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57453016/