【问题标题】:Java: importing from text file to ArrayList - out of bounds errorsJava:从文本文件导入到 ArrayList - 越界错误
【发布时间】:2015-07-14 08:46:59
【问题描述】:

我是一名学习 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 

【问题讨论】:

    标签: java arraylist indexoutofboundsexception


    【解决方案1】:

    您必须改用objRefList.add()objRefList.get(i).setName(temp); 行不工作,因为 arrayList 为空。

    您可能需要在openFileList 方法中执行类似的操作:

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

    【讨论】:

    • 抱歉,我该把它放在哪里?
    • 我试过了,它编译了,但它不会显示文本文件中的任何数据。
    • 您的 openFileList 方法也存在范围问题。尝试删除 ArrayList objRefList = new ArrayList();
    • 如果它对您有用,您可以接受答案。 ;) 不客气。
    • 另外,你知道我将如何使用 setMarks 方法将整数值导入到标记数组中吗?
    【解决方案2】:

    应该使用 Student 类,使用数组,用于存储保存在 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;
    }
    

    我在使用 OOP 而非结构化管理文件的班级中做到了这一点。更灵活。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 2013-10-13
      • 2013-04-02
      • 1970-01-01
      相关资源
      最近更新 更多