我在使用 java 数组时遇到了一些麻烦,希望得到一些帮助。我正在尝试制作一个程序,该程序将从 3 个文件中获取信息 - 一个包含学生姓氏,一个包含他们的 gpa,一个包含他们的学号。但是,当我运行该程序时,我得到上述 ArrayIndexOutOfBoundsException 为:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Final.loadArrays(Final.java:40) at Final.main(Final.java:25)我已经确保文件包含数据并且没有额外的空格等。请在下面找到我的代码,感谢您的帮助。import java.util.Scanner;import java.io.FileNotFoundException;import java.io.FileReader;import javax.swing.JOptionPane;public class studentinfo{public static void main(String [] args) throws FileNotFoundException{final int MAX_SIZE = 3;String[] names = new String[MAX_SIZE];double[] gpa = new double[MAX_SIZE];int[] studentNumber = new int[MAX_SIZE];loadArrays(names, gpa, studentNumber);}public static void loadArrays(String[] names, double[] gpa, int[] studentNumber) throws FileNotFoundException{ Scanner namesInFile = new Scanner(new FileReader ("names.txt")); Scanner gpaInFile = new Scanner(new FileReader ("gpa.txt")); Scanner studentNumberInFile = new Scanner(new FileReader ("studentNumber.txt")); int i = 0; //loop for loading names array while(namesInFile.hasNext()) { names[i] = namesInFile.next(); i++; } i = 0; //loop for loading gpa array while (gpaInFile.hasNext()) { gpa[i] = gpaInFile.nextDouble(); i++; } i = 0; //loop for loading student number array while (studentNumberInFile.hasNext()) { studentNumber[i] = studentNumberInFile.nextInt(); i++; } namesInFile.close(); gpaInFile.close(); studentNumberInFile.close(); for(i = 0; i < names.length ; i++) System.out.println(names[i]); for(i = 0; i < gpa.length ; i++) System.out.println(gpa[i]);
2 回答
![?](http://img1.sycdn.imooc.com/545847f50001126402200220-100-100.jpg)
www说
TA贡献1775条经验 获得超8个赞
3
是您的档案编号而不是档案中的学生人数。不要使用数组,因为您不知道实际数字,请List
改用。
import java.util.ArrayList;
将数组更改为数组列表。
ArrayList<String> names = new ArrayList<>(); ArrayList<Double> gpa = new ArrayList<>(); ArrayList<Integer> studentNumber = new ArrayList<>();
使用add
和get(index)
。
names.add(namesInFile.next());
和
System.out.println(names.get(i));
添加回答
举报
0/150
提交
取消