/**
 * @(#)RandomAccessFileTest.java
 *
 *
 * @author if
 * @version 1.00 2007/3/26
 */
 
import java.io.RandomAccessFile; 
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
public class RandomAccessFileTest {
    public static void main(String[] args) throws Exception{
        int nStu=Integer.parseInt(JOptionPane.showInputDialog(null,"你有多少个学生?"));
        Student stu=null;
        RandomAccessFileWriteRead ranWriteReadFile=new RandomAccessFileWriteRead("stu.txt");
        
        for(int i=0;i<nStu;i++){
            int id=Integer.parseInt(JOptionPane.showInputDialog(null,"第"+(i+1)+"个学生的ID是"));
            double grade=Double.parseDouble(JOptionPane.showInputDialog(null,"第"+(i+1)+"个学生的Grade是"));
            stu=new Student();
            stu.setID(id);
            stu.setGrade(grade);
            ranWriteReadFile.writeRandomFile(stu);
        }
        
        while(true){
            int id=Integer.parseInt(JOptionPane.showInputDialog(null,"你要查看第几个学生的成绩?输入-1退出!"));
            if(id==-1) break;
            String result=ranWriteReadFile.readRandomFile(id);
            System.out.println(result);
        }
    }
}
class RandomAccessFileWriteRead {
    private RandomAccessFile randomFile=null;
    private File file=null;
    
    public RandomAccessFileWriteRead(String filename){
        file=new File(filename);
    }
    
    public void writeRandomFile(Student stu) throws IOException{
        randomFile=new RandomAccessFile(file,"rw");
        long point=randomFile.length();
        randomFile.seek(point);
        int id=stu.getID();
        double grade=stu.getGrade();
        randomFile.writeInt(id);
        randomFile.writeDouble(grade);
        randomFile.close();
    }
    
    public String readRandomFile(int n) throws IOException{
        randomFile=new RandomAccessFile(file,"r");
        randomFile.seek((n-1)*12);
        Student stu=new Student();
        stu.setID(randomFile.readInt());
        stu.setGrade(randomFile.readDouble());
        randomFile.close();
        return stu.toString();
    }
}
class Student {
    private int id;
    private double grade;
    
    public void setID(int id){
        this.id=id;
    }
    
    public int getID(){
        return this.id;
    }
    
    public void setGrade(double grade){
        this.grade=grade;
    }
    
    public double getGrade(){
        return this.grade;
    }
    
    public String toString(){
        return "ID: "+id+" Grade: "+grade;
    }
}