“只能迭代一个数组”

时间:2018-04-24 05:48:51

标签: java arraylist

链接到我用于I / O的学生记录的Marks.txt文件: enter link description here

我有一个学生类(包含1个int studentID和6个赋值浮点数),它应该填充另一个名为 CourseSection 的类(只是一个ArrayList of学生对象),它是一个ArrayList,带有学生对象。

因此,在从Marks.txt文件中读取数据后,每个学生对象都应该填充名为 CourseSection 的ArrayList。

我正在尝试编写search()方法,因此它会提示用户输入StudentID,然后这个int ID用于遍历Student对象的ArrayList,直到它.getID()== ID(一个用户输入)。那么,它需要显示相应的学生6分配分数(浮点数)。我得到了一个

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Can only iterate over an array or an instance of java.lang.Iterable

错误来自于for循环之后的“course2”。 java不是作为ArrayList读取这个吗?它应该是Student对象的ArrayList正确吗?因为你可以看到我首先创建名为“course2”的CourseSection对象,然后我从文件Marks.txt中读取并指定“course2”来等于这个CourseSection.loadFrom方法(该方法返回一个CourseSection对象)。

public static void search(){

        BufferedReader aFile;

        CourseSection course2 = new CourseSection(); //creates course object which is ArrayList of Student objects

        aFile = new BufferedReader( new FileReader("marks_test_no_empty_strings.txt"));
         course2 = CourseSection.loadFrom(aFile); // reads .txt into course ArrayList

        Scanner scanner =  new Scanner(System.in);
        int id;
        boolean foundStudent = true;


        System.out.print("Enter the Student's ID: ");
        id = enterID();

       for(Student s : course2) {
            if(s.getID() == id) {
                s.getA1();
                s.getA2();
                s.getA3();
                s.getA4();
                s.getMidterm();
                s.getFinalExam();
            }
            else
                System.out.println("ID not found!!!");
        }
 }

CourseSection 类如果有帮助:

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

public class CourseSection {
    private String name;
    private ArrayList<Student> students;

   /**
   * Initializes the ArrayList<Student>.
   */ 
  public CourseSection(String n)
  {
    name = n;
    students = new ArrayList<Student>();
  }

  public CourseSection()
  {
    students = new ArrayList<Student>();
  }

  /**
   * Will add a new student to the ArrayList.
   * @param s A Student object.
   */
  public void addStudent(Student s){
    students.add(s);
  }

  /**
   * Removes the selected student from the ArrayList.
   * @param s A Student object.
   */
  public void removeStudent(Student s){ 
    Iterator studentIterator = students.iterator();

    while(studentIterator.hasNext()){
      if(studentIterator.next() == s)
        studentIterator.remove();
    }
  }


  /**
   * Lists all the information for each student in the course section. 
   */
  public void listStudents(){

    for(Student s: students){
      System.out.println(s);  
    }  
  }

  /**
   * Reads aFile except for the header and continuously creates new student objects 
   * for a new CourseSection.
   * @param aFile File to read from.
   * @return CourseSection New CourseSection read from aFile
   */
  public static CourseSection loadFrom(BufferedReader aFile) throws IOException{
      //String line = aFile.readLine();
    CourseSection course = new CourseSection(aFile.readLine()); 
    aFile.readLine(); // skips line
    while (aFile.ready()) //read until no more available (i.e., not ready)
    { 

        course.addStudent(Student.loadFromST(aFile)); //read & add the student
        }

    return course;
  }

}

这是我用来测试学生类中的 loadFrom 方法,并在 CourseSection中测试 loadFrom 的文件

import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;

public class loadTester {

    private static void studentLoadTest() throws IOException {
        BufferedReader  file1;
        Student student1; // student object
        //String line;

        file1 = new BufferedReader(new FileReader("marks_test_no_empty_strings.txt"));

        file1.readLine(); // skips 1st line
        file1.readLine(); // skips 2nd line

        /*
        while(file1.ready())
        {
            System.out.println(file1.readLine());
        }
        */

       /* while((line = aFile.readLine()) != null) {
            System.out.println(line);
        }
        */
       student1 = Student.loadFromST(file1); // using String Split
       System.out.println(student1); // This method individually parses it

       //file1.close();
    }

     private static void courseLoadTest() throws IOException {

            //String line;
         //CourseSection course = new CourseSection();

            BufferedReader aFile = new BufferedReader(new FileReader("marks_test_no_empty_strings.txt"));

            CourseSection course = CourseSection.loadFrom(aFile);
           // course.loadFrom(aFile);
            course.listStudents(); // this outputs the STUDENT OBJECTS IN THE ARRAY LIST!

            //course = CourseSection.loadFrom(aFile);
            //aFile.close();
        }

     public static void search(){

            BufferedReader aFile;

            CourseSection course2 = new CourseSection(); //creates course object which is ArrayList of Student objects

            aFile = new BufferedReader( new FileReader("marks_test_no_empty_strings.txt"));
             course2 = CourseSection.loadFrom(aFile); // reads .txt into course ArrayList

            Scanner scanner =  new Scanner(System.in);
            int id;
            boolean foundStudent = true;


            System.out.print("Enter the Student's ID: ");
            id = enterID();

           for(Student s : course2) {
                if(s.getID() == id) {
                    s.getA1();
                    s.getA2();
                    s.getA3();
                    s.getA4();
                    s.getMidterm();
                    s.getFinalExam();
                }
                else
                    System.out.println("ID not found!!!");
            }
     }

            public static int enterID(){

                Scanner scanner = new Scanner(System.in);
                int id = 0;

                try{
                  System.out.print("Enter the student's ID: ");
                  id = scanner.nextInt();
                }catch(InputMismatchException e){
                  System.out.println("Error: InputMismatchException");
                  id = enterID();
                }

                return id;
              }


    public static void main(String[] args) throws IOException
    {
        System.out.println("Testing Student Object I/O Stream:");
        studentLoadTest(); // testing to see if it outputs 1 Student Object per line
        System.out.println();
        System.out.println("Testing CourseSection creating ArrayList of Student Objects I/O Stream:");
        courseLoadTest(); // this should output the Entire marks.txt file as an ArrayList of Student objects
        search();
    }
}

3 个答案:

答案 0 :(得分:0)

course2不可迭代(CourseSection不实现Iterable)。

要迭代course2的学生,请在CourseSection课程中添加一个getter:

public List<Student> getStudents() {
    return this.students;
}

并用

迭代它
for(Student s : course2.getStudents()) {

}

答案 1 :(得分:0)

问题是CourseSection类不可迭代或数组。如果你做了这个改变,你可以像这样使用它:

public class CourseSection implements Iterable<Student> {

    //adding the following method:
    @Override
    public Iterator<Student> iterator() {
        return this.students.iterator();
    } 

您还可以通过更改主叫代码直接在学生身上进行迭代:

//You must add the getStudents() getter in CourseSection
for(Student s : course2.getStudents()) {

}

答案 2 :(得分:0)

CourseSection类不是一个数组或列表,它不会像这样编译

CourseSection类:

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

  public class CourseSection {
    private String name;
    private ArrayList<Student> students;

    /**
     * Initializes the ArrayList<Student>.
     */
    public CourseSection(String n)
    {
      name = n;
      students = new ArrayList<Student>();
    }

    public CourseSection()
    {
      students = new ArrayList<Student>();
    }

    /**
     * Will add a new student to the ArrayList.
     * @param s A Student object.
     */
    public void addStudent(Student s){
      students.add(s);
    }

    /**
     * Removes the selected student from the ArrayList.
     * @param s A Student object.
     */
    public void removeStudent(Student s){
      Iterator studentIterator = students.iterator();

      while(studentIterator.hasNext()){
        if(studentIterator.next() == s)
          studentIterator.remove();
      }
    }


    /**
     * Lists all the information for each student in the course section. 
     */
    public void listStudents(){

      for(Student s: students){
        System.out.println(s);
      }
    }

    public ArrayList<Student> getStudents()
    {
      return students;
    }

    /**
     * Reads aFile except for the header and continuously creates new student objects 
     * for a new CourseSection.
     * @param aFile File to read from.
     * @return CourseSection New CourseSection read from aFile
     */
    public static CourseSection loadFrom(BufferedReader aFile) throws IOException{
      //String line = aFile.readLine();
      CourseSection course = new CourseSection(aFile.readLine());
      aFile.readLine(); // skips line
      while (aFile.ready()) //read until no more available (i.e., not ready)
      {

        course.addStudent(Student.loadFromST(aFile)); //read & add the student
      }

      return course;
    }

  }

搜索方法:

    public static void search(){

      BufferedReader aFile;

      CourseSection course2 = new CourseSection(); //creates course object which is ArrayList of Student objects

      aFile = new BufferedReader( new FileReader("marks_test_no_empty_strings.txt"));
      course2 = CourseSection.loadFrom(aFile); // reads .txt into course ArrayList

      Scanner scanner =  new Scanner(System.in);
      int id;
      boolean foundStudent = true;


      System.out.print("Enter the Student's ID: ");
      id = enterID();

      for(Student s : course2.getStudents()) {
        if(s.getID() == id) {
          s.getA1();
          s.getA2();
          s.getA3();
          s.getA4();
          s.getMidterm();
          s.getFinalExam();
        }
        else
          System.out.println("ID not found!!!");
      }
    }

学生班

public class Student {
  private int ID;
  private float a1;
  private float a2;
  private float a3;
  private float a4;
  private float midterm;
  private float finalExam;


  /**
   * The Default constructor is used to intialize all instance variables 
   * in the class to zero.
   */
  Student(){
    ID = 0;
    a1 = 0.0f;
    a2 = 0.0f;
    a3 = 0.0f;
    a4 = 0.0f;
    midterm = 0.0f;
    finalExam = 0.0f;
  }

  Student(int id, float a1, float a2, float a3, float a4, float midterm, float finalExam) {
    ID = id;
    this.a1 = a1;
    this.a2 = a2;
    this.a3 = a3;
    this.a4 = a4;
    this.midterm = midterm;
    this.finalExam = finalExam;
  }

//Set methods for all instance variables of Student 
  public void setID(int newID)
  { 
      ID = newID; 
  }

  public void setA1(float newA1)
  { 
      a1 = newA1; 
  }
  public void setA2(float newA2)
  { 
      a2 = newA2; 
  }
  public void setA3(float newA3)
  { 
      a3 = newA3; 
  }
  public void setA4(float newA4)
  { 
      a4 = newA4; 
  }

  public void setMidterm(float newMidterm) // Typo was here for Mideterm
  { 
    midterm = newMidterm; 
  } 

  public void setFinalGrade(float newFinal)
  { 
     finalExam = newFinal; 
  }

  //Get methods for instance variables of Student
  public int getID()
  {
      return ID; 
  }
  public float getA1()
  { 
      return a1; 
  } 
  public float getA2()
  { 
      return a2; 
      }
  public float getA3()
  { 
      return a3; 
  }
  public float getA4()
  { 
      return a4; 
  }
  public float getMidterm()
  { 
      return midterm; 
  }
  public float getFinalExam()
  { 
      return finalExam; 
  }


  /**
   * Prints all instance variables as a string.
   * @return A string representing the student.
   */
  public String toString(){
    return(ID + ": " + a1 + " " + a2 + " " + a3 + " " + a4 + " " + midterm + " " + finalExam);
  }


  /**
   * Will read from the linked file which will create and return a new Student object.
   * @param aFile File to read from.
   * @return A new Student object read from a line of the file.
 * @throws IOException 
 * @throws NumberFormatException 
   */


  //using StringTokenizer
  public static Student loadFromST(BufferedReader aFile) throws IOException {
    Student newStudent = new Student();
    //int i = 0;
    //String zero = "0";

    StringTokenizer st = new StringTokenizer(aFile.readLine()," ");

    //while(st.hasMoreTokens()) {
        //if(st.nextToken().isEmpty())
         //zero = st.nextToken();
            //else {
    newStudent.ID = Integer.parseInt(st.nextToken());
    newStudent.a1 = Float.parseFloat(st.nextToken());
    newStudent.a2 = Float.parseFloat(st.nextToken());
    newStudent.a3 = Float.parseFloat(st.nextToken());
    newStudent.a4 = Float.parseFloat(st.nextToken());
    newStudent.midterm = Float.parseFloat(st.nextToken());
    newStudent.finalExam = Float.parseFloat(st.nextToken());
    //i++;
            //}
   // }
    return (newStudent);
  } 


  //using Split String
  /*
  public static Student loadFromSS(BufferedReader aFile) throws java.io.IOException {
      Student newStudent = new Student();
      String[] words = aFile.readLine().split(" "); // can't split for anything bigger than 1 space

      //for(int i = 0; i <= words.length; i++) {
        // if(words[i].isEmpty()) 
        // words[i] = "0";
        // } 

      newStudent.ID = Integer.parseInt(words[0]);
      newStudent.a1 = Float.parseFloat(words[1]);
      newStudent.a2 =  Float.parseFloat(words[2]);
      newStudent.a3 = Float.parseFloat(words[3]);
      newStudent.a4 = Float.parseFloat(words[4]);
      newStudent.midterm = Float.parseFloat(words[5]);
      newStudent.finalExam = Float.parseFloat(words[6]);

  return newStudent;
}*/

}