我正在尝试下一步,
我有一个数据量为n的数组,当我单击名为“下一个”的按钮时,每次单击该按钮时,该数组都会移动到下一个循环的元素。
但是我有一个名为“上一个”的按钮,出于明显的原因,它的作用相反。这里的问题是,当元素处于开始位置并且需要移动到最后一个位置时,我得到以下错误
java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
这是我的全部代码
public class MainActivity extends AppCompatActivity {
private TextView mStudentEditText;
private Button mNext;
private Button mPrevious;
private Student[] mStudents= new Student[]{
new Student(111,"Carlos",100),
new Student(222,"Ana",60),
new Student(333,"Luis",95)
};
private int mCurrentIndex = 0;
private void updateStudent() {
mStudentEditText.setText("Numero de control: " + mStudents[mCurrentIndex].getNoControl()+"\n"+
"Nombre: " + mStudents[mCurrentIndex].getName()+"\n"+
"Calificacion: " + mStudents[mCurrentIndex].getScore());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStudentEditText = findViewById(R.id.student_textview);
mNext = findViewById(R.id.next_button);
mPrevious = findViewById(R.id.previous_button);
updateStudent();
mNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex=(mCurrentIndex+1)%(mStudents.length);
updateStudent();
}
});
mPrevious.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex - 1) % (mStudents.length);
updateStudent();
}
});
}
}
答案 0 :(得分:2)
这是由于mCurrentIndex = (mCurrentIndex - 1) % (mStudents.length);
单击上一个按钮时,将生成currentIndex = -1
。因此,updateStudent访问-1
索引。因此,发生以下错误。
为防止这种情况,您可以这样做
if(mCurrentIndex > 0)
mCurrentIndex = (mCurrentIndex - 1) % (mStudents.length);
else
mCurrentIndex = 0;