循環將只運行兩次 - 如果輸入一個無效的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])
爲做循環的結束,但隨後它提供了一個數組索引越界異常。
該分配需要平行陣列。 –