2015-03-08 25 views
0

我正在尝试通过让用户输入标识号来访问并行数组的全部内容。该数组似乎只返回前四项[0-3]的结果。剩余部分由于未找到而返回。使用Eclipse,我试图将数组完全标注到10个内存位置,但是,我收到错误。如何访问java中的并行数组的全部内容?

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); 
      } 
     } 
    } 
} 

回答

4

在for循环变化:

studentId.length(); 

studentNum.length; 

您现在正在使用的输入字符串的长度,而你需要在数组的长度。

3

难道你不应该迭代for循环中的“studenNum”数组吗?你有一个错误/错误,你正在迭代错误的变量。

2

请您for循环看:

for (int x = 0; x < studentId.length(); ++x) 

而不是使用您的studentNum数组的长度,您使用的用户输入studentId这是最容易长4个字符(由于长度的给予studentNum的学生ID)。这就是为什么你的程序只能找到索引0 - 3的条目(该阵列似乎只返回前四项[0-3])的结果。

将其更改为

for (int x = 0; x < studentNum.length; ++x) 

修复它。