2014-12-05 2 views
1

В варианте два и три я не имею понятия, как ссылаться на сериализованный arraylist для определенных типов данных (то есть имя строки или двойной gpa), а затем сравнивать их. На лабораторном листе мы получили инструкции о том, как делать все остальное, но для выполнения вариантов 2 и 3 он буквально сказал «разобраться», профессор никогда не умел объяснять вещи классу. Поэтому я надеюсь, что кто-нибудь сможет объяснить это мне.Как выбрать определенные объекты из сериализованного массива?

Edit: 901 номер, что студент ID номера называются в моем университете

Вот мой класс Student (все должно быть хорошо в нем)

import java.io.Serializable; 
public class Student implements Serializable 
{ 
    private String lastName, firstName; 
    private double gpa; 
    private int studentID, gradYear; 
    public Student(int studentID, String lastName, String firstName, double gpa, int gradYear) 
    { 
     this.studentID = studentID; 
     this.lastName = lastName; 
     this.firstName = firstName; 
     this.gpa = gpa; 
     this.gradYear = gradYear; 
    } 
    public int getStudentID() 
    { 
     return studentID; 
    } 
    public String getLastName() 
    { 
     return lastName; 
    } 
    public String getFirstName() 
    { 
     return firstName; 
    } 
    public double getGPA() 
    { 
     return gpa; 
    } 
    public int getGradYear() 
    { 
     return gradYear; 
    } 
    public String toString() 
    { 
     return "Student ID: " + studentID + " Name: " + lastName.trim() + ", " + firstName.trim() + " GPA: " + gpa + " Grad year: " + gradYear; 
    } 
} 

Вот тестовый класс, где мне нужна помощь (за пределами вариантов 2 & 3 Я думаю, что все это работает)

import java.util.*; 
import java.io.*; 
public class StudentTestOS 
{ 
    public static void main(String[] args) throws IOException, ClassNotFoundException 
    { 
     boolean done = false; 
     ArrayList<Student> sList = new ArrayList<Student>(); 
     File sFile = new File("studentOS.dat"); 
     if(sFile.exists()) 
     { 
      FileInputStream myFIS = new FileInputStream(sFile); 
      ObjectInputStream sIn = new ObjectInputStream(myFIS); 
      sList = (ArrayList<Student>)sIn.readObject(); 
      sIn.close(); 
     }  
     System.out.println("Students on file: "); 
     for(int i = 0; i < sList.size(); i++) 
      System.out.println(sList.get(i).toString()); 
     do 
     { 
     Scanner myScanner = new Scanner(System.in);   
     while (!done) 
     { 
      System.out.println("1 - add a student"); 
      System.out.println("2 - display student info"); 
      System.out.println("3 - display student info given their last name"); 
      System.out.println("4 - exit"); 
      int choice = Integer.parseInt(myScanner.nextLine()); 
      if (choice == 1) 
      { 
       System.out.print("Enter 901 number: "); 
       int studentID = Integer.parseInt(myScanner.nextLine()); 
       System.out.print("Enter last name: "); 
       String lastName = myScanner.nextLine(); 
       System.out.print("Enter first name: "); 
       String firstName = myScanner.nextLine(); 
       System.out.print("Enter gpa: "); 
       double gpa = Double.parseDouble(myScanner.nextLine()); 
       System.out.print("Enter grad year: "); 
       int gradYear = Integer.parseInt(myScanner.nextLine()); 
       Student myStudent = new Student(studentID, lastName, firstName, gpa, gradYear); 
       sList.add(myStudent); 
      } 
      else if (choice == 2) 
      { 
       System.out.print("Enter 901 number: "); 
       int studentID = Integer.parseInt(myScanner.nextLine()); 
      } 
      else if (choice == 3) 
      { 
       System.out.println("Enter last name: "); 
       String lastName = myScanner.nextLine(); 
      } 
      else if (choice == 4) 
      { 
       done = true; 
      } 
      else 
       System.out.println("Invalid menu choice!"); 
     } 
     System.out.println("Goodbye!"); 
    }while(!done); 
    FileOutputStream myFOS = new FileOutputStream(sFile); 
    ObjectOutputStream sOut = new ObjectOutputStream(myFOS); 
    sOut.writeObject(sList); 
    sOut.close(); 
} 
} 

ответ

0

Вы можете иметь цикл и сравнения объектов по одному на данных атрибутов (Id Ф.О. r choice2 и lastName для выбора 3).

Для выбора 2: -

System.out.print("Enter 901 number: "); 
int studentID = Integer.parseInt(myScanner.nextLine()); 
for(Student student : sList){ 
    if(student.getStudentID == studentId){ 
    System.out.println(student); 
    break; // As student Id is unique.So, once we found the student no need to loop further. 
    } 
} 

Для выбора 3, сравнивая его на LastName и не ставят заявление перерыв, так как может быть много с таким же LastName.

Смежные вопросы