循环只会运行两次 - 如果您输入无效id
两次,它将在第二次之后结束。没有错误,它只是以它认为应该的方式结束。我看不到哪里validID
变成true
了,因为它仍然不是id
数组中的数字之一。
import javax.swing.*;
public class StudentIDArray {
public static void main(String[] args) {
int[] id = {1121, 1234, 2864, 3141, 4650, 5167, 5678, 6044, 7737, 9101};
String[] name = {"Bryan", "Colleen", "David", "Frank", "Glennis", "Jerome", "Jessie", "Larry", "Steve", "Tina"};
double[] gpa = {3.7, 3.2, 2.9, 3.5, 2.4, 3.8, 3.9, 3.9, 2.6, 2.2};
final int STUDENTS = 10;
String idNumber;
int studentID;
double studentGPA = 0.0;
boolean validID = false;
String studentName = "";
int x;
do{
idNumber = JOptionPane.showInputDialog(null, "Enter the student ID number.");
studentID = Integer.parseInt(idNumber);
for(x = 0; x < STUDENTS; x++){
if(studentID == id[x]){
validID = true;
studentName = name[x];
studentGPA = gpa[x];
}
}
if(validID) {
JOptionPane.showMessageDialog(null, "ID number " + studentID + " belongs to " + studentName + " who has a GPA of " + studentGPA + ".");
} else {
JOptionPane.showMessageDialog(null, studentID + " is an invalid ID. Please try again.");
idNumber = JOptionPane.showInputDialog(null, "Enter the student ID number.");
}
}
while(validID = false);
}
}
当我尝试while(studentID != id[x])
结束 do 循环时,它会给出一个数组索引超出范围异常。