Reputation: 1
I am trying access the full contents of a parallel array by having the user enter an identification number. The array only seems to return results for the first four items [0-3]. The remainder are returned as not found. Using Eclipse, I tried to fully dimension the array to 10 memory locations, however, I get errors.
import java.util.*;
import javax.swing.JOptionPane;
public class StudentIDArray {
static String[] studentNum = new String[]
{"1234", "2345", "3456", "4567", "5678", "6789", "7890", "8901", "9012", "0123"};
static String[] studentName = new String[]
{"Peter", "Brian", "Stewie", "Lois", "Chris", "Meg", "Glen", "Joe", "Cleveland", "Morty"};
static double[] studentGpa = new double[]
{2.0, 3.25, 4.0, 3.6, 2.26, 3.20, 3.45, 3.8, 3.0, 3.33};
public static void main(String[] args) {
String studentId = null;
while ((studentId = JOptionPane.showInputDialog(null, "Please enter your Student ID number to view your name and GPA")) != null) {
boolean correct = false;
for (int x = 0; x < studentId.length(); ++x) {
if (studentId.equals(studentNum[x])) {
JOptionPane.showMessageDialog(null, "Your name is: " + studentName[x] + "\n" + "Your GPA: " + studentGpa[x], "GPA Results", JOptionPane.INFORMATION_MESSAGE);
correct = true;
break;
}
}
if (!correct) {
JOptionPane.showMessageDialog(null, "Student ID not found, try again.", "Not found", JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
Upvotes: 0
Views: 490
Reputation: 966
In the for loop change:
studentId.length();
to
studentNum.length;
You are now using the length of the input string while you need to the length of the array.
Upvotes: 4
Reputation: 17587
Please look at your for
loop:
for (int x = 0; x < studentId.length(); ++x)
Instead of using the length of your studentNum
array, you're using the length of the user input studentId
which is most likely 4 characters long (due to your given student ids in studentNum
). That is why your program only find entries on index 0 - 3 (The array only seems to return results for the first four items [0-3]).
Change it to
for (int x = 0; x < studentNum.length; ++x)
to fix it.
Upvotes: 2
Reputation: 2398
Shouldn't you be iterating over the "studenNum" array in your for loop? You have a typo/bug where you are iterating over the wrong variable.
Upvotes: 3