2012-08-10 3 views
0

안녕하세요 내 randomAccessFile 애플리케이션이 학생을 파일에 추가하고 있지 않습니다. arrayList를 사용하여 학생 저장소를 설정했고 추가 된 학생이 저장소에 추가되고 있지만 "ContactDetails.txt"파일에 표시되지 않습니다. 누구든지 잘못된 것을 볼 수 있습니까? 추가하지 않는 메소드 추가 RandomAccessFile의 학생

import java.io.Serializable; 

public class Student implements Serializable 
{ 
//--------------------------------------------------------------------------- 
// Class Variables. 
//--------------------------------------------------------------------------- 
    private String studentName; 
    private String studentId; 
    private String studentTelephoneNumber; 
    private String studentEmail; 
//--------------------------------------------------------------------------- 
// Constructor. 
//--------------------------------------------------------------------------- 
    public Student(String studentName, String studentId,String studentTelephoneNumber, String studentEmail) 
    { 
     this.studentName = studentName; 
     this.studentId = studentId; 
     this.studentTelephoneNumber = studentTelephoneNumber; 
     this.studentEmail = studentEmail; 
    } 
//--------------------------------------------------------------------------------------- 
// Overloading the constructor for the use with userInputByName method. 
//--------------------------------------------------------------------------------------- 
    public Student(String studentName) 
    { 
     this.studentName = studentName; 
    } 
//--------------------------------------------------------------------------- 
// Getters. 
//--------------------------------------------------------------------------- 
    public String getStudentName() 
    { 
     return studentName; 
    } 
    public String getStudentId() 
    { 
     return studentId; 
    } 
    public String getStudentTelephoneNumber() 
    { 
     return studentTelephoneNumber; 
    } 
    public String getStudentEmail() 
    { 
     return studentEmail; 
    } 
//--------------------------------------------------------------------------- 
// Setters. 
//--------------------------------------------------------------------------- 
    public void setStudentName(String studentName) 
    { 
     this.studentName = studentName; 
    } 
    public void setStudentId(String studentId) 
    { 
     this.studentId = studentId; 
    } 
    public void setStudentTelephoneNumber(String studentTelephoneNumber) 
    { 
     this.studentTelephoneNumber = studentTelephoneNumber; 
    } 
    public void setStudentEmail(String studentEmail) 
    { 
     this.studentEmail = studentEmail; 
    } 
//--------------------------------------------------------------------------- 
// toString. 
//--------------------------------------------------------------------------- 
    public String toString() 
    { 
     return "---------------------------Student--------------------------- " + 
       "\nStudent Name:" + studentName + 
       "\nStudent Id:"+ studentId + 
       "\nStudent Telephone Number:"+ studentTelephoneNumber + 
       "\nStudent Email:" + studentEmail +"\n\n"; 
    } 


} 
학생

MainApp

import java.io.IOException; 
import java.io.RandomAccessFile; 
import java.util.Scanner; 



public class MainApp 
{ 
//--------------------------------------------------------------------------------------- 
// The Scanner is declared here for use throughout the whole MainApp. 
//--------------------------------------------------------------------------------------- 
    private static Scanner keyboard = new Scanner(System.in); 

    public static void main(String[] args) throws Exception 
    { 
     new MainApp().start(); 

    } 
    public void start()throws Exception 
    { 
     StudentStore details = new StudentStore(); 
     Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "[email protected]"); 
     Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "[email protected]"); 
     Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "[email protected]"); 
     Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "[email protected]"); 
     Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "[email protected]"); 
     details.add(a); 
     details.add(b); 
     details.add(c); 
     details.add(d); 
     details.add(e); 
     //details.print(); 


     RandomAccessFile file = new RandomAccessFile("ContactDetails.txt","rw"); 
     //getBytes() returns an array of bytes. 
     //Because i have put the store in a static Array.(I done this because i could find no other 
     //Simple way to write a Student Object.) 
     //None of the methods of the RandomAccessFile write class worked with this. 
     //Student[] students = {a,b,c,d,e}; 
     details.write(file); 
     //details.readAll(file); 
     int choice; 
     System.out.println("Welcome to the Company Database."); 
     do 
     { 
      choice = MenuMethods.getMenuChoice("1.\tView" + 
               "\n2.\tAdd"+ 
               "\n3.\tDelete" + 
               "\n4.\tDelete All " + 
               "\n5.\tEdit"+ 
               "\n6.\tSearch" + 
               "\n7.\tStore" + 
               "\n8.\tExit", 8, 
               "Please enter your choice:", "Error [1,8] Only"); 
     // String temp = keyboard.nextLine(); This prevented entering the choice. 
     //--------------------------------------------------------------------------------------- 
//   Name:  Switch Statement. 
//   Description: This is used for a menu system. 
     //--------------------------------------------------------------------------------------- 
        switch (choice) 
        { 
     //--------------------------------------------------------------------------------------- 
//   Name:  Case 1: View All 
//   Description: Choice 1 is to view all employee's in the store. 
     //--------------------------------------------------------------------------------------- 
        case 1: 
         System.out.println("View All"); 
         details.readAll(file); 
         break; 
     //--------------------------------------------------------------------------------------- 
//   Name:  Case 2: Add 
//   Description: Choice 2 is to add an employee to the store. 
     //--------------------------------------------------------------------------------------- 
        case 2: 
         System.out.println("Add"); 
         Student student = MenuMethods.userInput(); 
         details.add(student); 
         break; 
     //--------------------------------------------------------------------------------------- 
//   Name:  Case 3: Delete by Name. 
//   Description: Choice 3 gives the user an option to delete an employee by name. 
     //--------------------------------------------------------------------------------------- 
        case 3: 
         System.out.println("Delete by Name."); 
         //Employee employeeDelete = MenuMethods.userInputByName(); 
         //Store.searchByName(employeeDelete.getEmployeeName()); 
         //Store.remove(employeeDelete.getEmployeeName()); 
         break; 
     //--------------------------------------------------------------------------------------- 
//      Name:  Case 4: Delete All. 
//      Description: Choice 4 gives the user a choice to delete all employee's in the store. 
     //--------------------------------------------------------------------------------------- 
        case 4: 
         System.out.println("Delete All."); 
         //Store.clear(); 

         break; 
     //--------------------------------------------------------------------------------------- 
//      Name:  Case 4: Edit. 
//      Description: Choice 4 gives the user an option to edit the employee's in the store. 
//         This consists of changing the employee's name,id and e-mail address. 
     //--------------------------------------------------------------------------------------- 
        case 5: 
         System.out.println("Edit"); 

         break; 

     //--------------------------------------------------------------------------------------- 
//   Name:  Case 6: Search. 
//   Description: Choice 6 gives the user 2 options: Search by name and Search by email. 
//      Search will run through the store and output the employee match the user inputs. 
     //--------------------------------------------------------------------------------------- 
        case 6: 

         break; 
     //--------------------------------------------------------------------------------------- 
//   Name:  Case 7: Store. 
//   Description: Choice 7 gives the user an option to copy and read a store 
//      using read and write class from Java. 
     //--------------------------------------------------------------------------------------- 
        case 7: 


         break; 
     //--------------------------------------------------------------------------------------- 
//   Name:  Case 8: Exit. 
//   Description: Choice 8 will exit the application. 
     //--------------------------------------------------------------------------------------- 
        case 8: 
         System.out.println("Exit"); 

         break; 
        } 

       } while (choice != 8); 



     file.close(); 
    } 


} 

StudentStore

//--------------------------------------------------------------------------- 
//Imports. 
//--------------------------------------------------------------------------- 
import java.io.IOException; 
import java.io.RandomAccessFile; 
import java.util.ArrayList; 
import java.util.List; 
//--------------------------------------------------------------------------- 

public class StudentStore 
{ 
//--------------------------------------------------------------------------- 
//ArrayList declaration. 
//--------------------------------------------------------------------------- 
    List<Student> students = new ArrayList<Student>(); 
//--------------------------------------------------------------------------- 
//Name:   Add method. 
//Description: Adds a student to the ArrayList. 
//--------------------------------------------------------------------------- 
    public void add(Student student) 
    { 
     students.add(student); 
    } 
//--------------------------------------------------------------------------- 
//Name:   DeleteAll method. 
//Description: Delete's everything in the ArrayList. 
    //--------------------------------------------------------------------------- 
    public void deleteAll() 
    { 
      students.clear(); 
    } 
//--------------------------------------------------------------------------- 
//Name:   Print method. 
//Description: Prints out the contents of the ArrayList. 
//--------------------------------------------------------------------------- 
    public void print() 
    { 
     for (int i = 0; i < students.size(); i++) 
     { 
      Student a = students.get(i); 
      System.out.println(a.toString()); 
     } 
    } 
    public int size() 
    { 
     return (students == null) ? 0 : students.size(); 
    } 
    public void write(RandomAccessFile file) throws IOException 
    { 
     for (Student s: students) 
     { 
      byte[] bytes = s.toString().getBytes(); 
      for(byte byteWrite : bytes) 
      { 
       file.writeByte(byteWrite); 
      } 
     } 

    } 

    public void readAll(RandomAccessFile file) throws IOException 
    { 
     final int Record_Length = 30; 
     int recordNumber = 0; 
     file.seek((recordNumber) * Record_Length); 

     String code =""; 
     for(int i = 0; i < 30; i++) 
     { 
     code += file.readLine() + "\n"; 
     } 
     System.out.println(code); 
    } 

} 

MenuMethods

//--------------------------------------------------------------------------------------- 
// Name:   Imports. 
// Description: To allow the use of different Java classes. 
//--------------------------------------------------------------------------------------- 
import java.util.Scanner; 
//--------------------------------------------------------------------------------------- 

public class MenuMethods 
{ 
    private static Scanner keyboard = new Scanner(System.in); 
//--------------------------------------------------------------------------------------- 
// Methods for the Company Application menu. 
//--------------------------------------------------------------------------------------- 

//--------------------------------------------------------------------------------------- 
// Name:   getMenuChoice. 
// Description: Method for validating the choice. 
//--------------------------------------------------------------------------------------- 
    public static int getMenuChoice(String menuString, int limit,String prompt, String errorMessage) 
    { 
     System.out.println(menuString); 
     int choice = inputAndValidateInt(1, limit, prompt, errorMessage); 
     return choice; 
    } 

//--------------------------------------------------------------------------------------- 
// Name:  inputAndValidateInt. 
// Description: This method is used in the getMenuChoice method. 
//--------------------------------------------------------------------------------------- 
    public static int inputAndValidateInt(int min, int max, String prompt,String errorMessage) 
    { 
     int number; 
     boolean valid; 
     do 
     { 
      System.out.print(prompt); 
      number = keyboard.nextInt(); 
      valid = number <= max && number >= min; 
      if (!valid) 
      { 
       System.out.println(errorMessage); 
      } 
     } while (!valid); 
     return number; 
    } 

//--------------------------------------------------------------------------------------- 
// Name:  userInput 
// Description: This method is used in the MainApp to give the user capability to enter 
//    the details when adding details of an employee into the store. 
//--------------------------------------------------------------------------------------- 
    public static Student userInput() 
    { 
     String temp = keyboard.nextLine(); 
     Student s = null; 
     System.out.println("Please enter the Student Name:"); 
     String studentName = keyboard.nextLine(); 
     System.out.println("Please enter the Student ID:"); 
     String studentId = keyboard.nextLine(); 
     System.out.println("Please enter the Student E-mail address:"); 
     String studentEmail = keyboard.nextLine(); 
     System.out.println("Please enter the Student telephone number:"); 
     String studentTelephoneNumber = keyboard.nextLine(); 
     return s = new Student(studentName, studentId, studentEmail,studentTelephoneNumber); 

    } 

//--------------------------------------------------------------------------------------- 
// Name:  userInputByName. 
// Description: This method is used in the MainApp to give the user capability to search by name. 
//--------------------------------------------------------------------------------------- 
    public static Student userInputByName() 
    { 
     // String temp is for some reason needed. If it is not included 
     // The code will not execute properly. 
     String temp = keyboard.nextLine(); 
     Student s = null; 
     System.out.println("Please enter the Student Name:"); 
     String studentName = keyboard.nextLine(); 

     return s = new Student(studentName); 

    } 

//--------------------------------------------------------------------------------------- 
// Name:  userInputByEmail 
// Description: This method is used in the MainApp to give the user capability to search by email. 
//--------------------------------------------------------------------------------------- 
    public static String userInputByEmail() 
    { 
     // String temp is for some reason needed. If it is not included 
     // The code will not execute properly. 
     String temp = keyboard.nextLine(); 
     Student s = null; 
     System.out.println("Please enter the StudentEmail:"); 
     String studentEmail = keyboard.nextLine(); 
     // This can use the employeeName's constructor because java accepts the 
     // parameters instead 
     // of the name's. 
     return studentEmail; 

    } 
//--------------------------------------------------------------------------------------- 
} 

: 여기

내 코드입니다

답변

1

내가 입력 한, 당신이 당신의 주요 방법으로 입력이있는 모든 학생 정보를 인쇄 할 경우 내가 테스트하면 코드가 학생 클래스 코드는 학생 클래스

에서 toString() 메서드를 재정의하는지 여부를 을 게시하시기 바랍니다. 하지만 2를 입력하면 Student 정보를 입력 한 후 Arraylist의 정보를 메모리에 추가하고 파일에 출력하지 않습니다. 그래서 1을 입력하면 이전에 입력 한 새로운 학생 정보가 출력되지 않습니다.

파일을 출력하기 위해 새로운 학생 정보가 필요하다고 생각합니다. 당신은 모든 방법 변화를 읽기에

편집

case 2: 
         System.out.println("Add"); 
         Student student = MenuMethods.userInput(); 
         details.add(student); 
         break; 

case 2: 
         System.out.println("Add"); 
         Student student = MenuMethods.userInput(); 
         details.add(student); 
file.write(student.toString().getBytes()); 
        break; 

과에 더는 파일의 처음 30 라인을 읽고

public void readAll(RandomAccessFile file) throws IOException 
    { 
     final int Record_Length = 30; 
     int recordNumber = 0; 
     file.seek((recordNumber) * Record_Length); 

     String code =""; 
     for(int i = 0; i < 30; i++) 
     { 
     code += file.readLine() + "\n"; 
     } 
     System.out.println(code); 
    } 

public void readAll(RandomAccessFile file) throws IOException 
    { 
     file.seek(0); 

     String code; 
while((code=file.readLine())!=null) 
     System.out.println(code); 
    } 
+0

내가 거기에서 편집했습니다. – Pendo826

+0

감사 인사는 매력처럼 일했습니다. readAll 메서드가 정확히 무엇인지 물어볼 수 있습니까? 파일에서 – Pendo826

+0

readAll 학생 정보를 읽으십시오. – andy