Java:从文本文件导入到ArrayList – 超出范围错误

我是一名学习
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(). objRefList.get(i).setName(temp)行;由于arrayList为空,因此无法正常工作.

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

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