Java: 从文本文件导入 ArrayList - 越界错误

Java: importing from text file to ArrayList - out of bounds errors

我是一名学习 java 的学生,我很难弄清楚为什么会出现越界错误。关于如何编码的任何输入 openFileList(); 方法会非常有用。

准确的错误是:

    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at MathClassMrA.openFileList(ps25openfilemra.java:100)
    at PS25OpenFileMrA.main(ps25openfilemra.java:9)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

代码如下:

import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;

class PS25OpenFileMarian {

  public static void main(String [] arg) throws IOException {  // note throws IOException in main()
       MathClassMarian objA = new MathClassMarian();
       objA.openFileList();   //  You need to code this method
       objA.displayArrayList();
       //objA.openFileArray();   // You need to code this method.
      // objA.displayArrayObjects();

       } // ---------end of main() -----------------------
}  // ######### end of PS25OpenFile Program ################################
 /* **************************************************************************
  * @Author:  Marian     @Date: today
  * This class is design to hold data that can be manipulated by it's child class.
  * ************************************************************************* */

  class Student {
  //INSTANCE VARIABLES
  private String name;
  private int [] marks;

//CONSTRUCTORS
  Student() 
  {// default 
    name = null; 
    marks = new int[10];
    for (int i=0; i < marks.length; i++)
          marks[i] = -1;
  }
  //INSTANCE METHODS
  public String getName() { return name; }
  public void setName(String N) { name = N; }
  public int getMark(int index) { return marks[index]; }
  public void setMark(int index, int M) { marks[index] = M; }

  public void displayInfo() {
       System.out.println("--------------------");
       System.out.printf("Name of Student: %s \n", name);
       System.out.println("====Marks===");
       for (int i=0; i < marks.length; i++)
             if (marks[i] != -1)
                  System.out.printf("Mark %d: = %d \n " , i+1, marks[i]);
        System.out.printf("Overall Average: = %.2f \n", calcAverage());
  }  //---end of displayInfo() method 

  public double calcAverage() {
          double average = 0;
          int NoOfTests = 0;
          for (int i=0; i < marks.length; i++)
          {
            if (marks[i] != -1)
            {
                 average += marks[i];  // average = average + marks[i];
                 NoOfTests++;
            }

          }
   return (average/NoOfTests);
  } // --end of calcAverage() mMethod --
  }  // end of Student class

  /* *************************************************************************
   * @Author:  You    @Date:  Today
   * This class manipulates the data in either an Array of Objects or an ArrayList
   * ************************************************************************** */
  class MathClassMarian extends Student {
    //INSTANCE VARIABLES ----
    public static int records = 0;    // used to count the number of records in the Array of Objects.
    ArrayList<Student>  objRefList;

    Student [] objRefArray;
    //CONSTRUCTORS -------------
    MathClassMarian() 
    {  // default constructor
      objRefList = new ArrayList<Student>();  // array list null
      objRefArray = new Student[10];               // array of objects null.
    }
    //INSTANCE METHODS --------------
    /* *******************************************************************
     * Activity #1:  @Author:  You     @Date:  today      The method below should connect
     * to a file called studentdata.txt and load the information in the file into the ArrayList
     * call the method openFileList():  Note:  don't forget the throws IOException in the method
     * header.
     * @param: none   @return:  none
     * *******************************************************************/
    public void openFileList() throws IOException{
    File file = new File("studentdata.txt"); 
    Scanner scan = new Scanner (file);
  //  objRefList.add(new student()) ;
    ArrayList <Student> objRefList = new ArrayList<Student>();
    int i =0, j=0;
    String temp ;
    int temp2;
    while (scan.hasNext())  {
    temp = scan.nextLine();
    objRefList.get(i).setName(temp);                
    i++;     
    } 

  do  {  
    temp2 = scan.nextInt();
    objRefList.get(j).setMark(j,temp2);                
    j++;     
    } while (scan.hasNextInt());*/ 





    }
     /* *******************************************************************
     * Activity #2:  @Author:  You     @Date:  today      The method below should connect
     * to a file called studentdata.txt and load the information in the file into the Array of Objects
     * Call the file openFileArray().  Note:  need to increment records variable, it keeps track 
     * of the number of objects in my Array of Objects.  And of course don't forget the 
     * thows IOException in the method header.

    public void displayArrayList() 
    {
      System.out.println("ArrayList Information -------");
           for (int index = 0; index < objRefList.size(); index++)
                  objRefList.get(index).displayInfo();
      System.out.println("================");
    } //--------end of displayArrayList() method --------

    public void displayArrayObjects() 
    {
       System.out.println("Array of Objects Information ----------");
             for (int index = 0; index < records; index++)
                  objRefArray[index].displayInfo();    
      System.out.println("===============");

    } // -------end of displayArrayObjects() method  -----

  }  // end of Student class 

您必须改为使用 objRefList.add()。由于 arrayList 为空,行 objRefList.get(i).setName(temp); 不起作用。

您可能需要在 openFileList 方法中执行以下操作:

Student student = new Student();
student.setName(temp);
objRefList.add(student);

应该使用 Student class,使用数组来存储 RandomAccessFile 中保存的对象,并像这样打印:

public Persona[] readAll()throws IOException{
    Persona[] n = new Persona[this.N];

    for(int i=0;i<n.length;i++){
        pos = 4+i*MAX;
        raf.seek(pos);

        Persona p1 = new Persona();

                    p1.setNombre(raf.readUTF());
                    p1.setApellido(raf.readUTF());
                    p1.setEdad(raf.readInt());
                    p1.setTelefono(raf.readInt());
        n[i]=p1;
    }
    return n;
}

我在 class 中使用非结构化的 OOP 管理文件。更灵活。