繁体   English   中英

在随机访问文件中添加数据:java gui

[英]Add data in a random access file:java gui

我正在尝试创建一个可以添加,更新,查看,删除和搜索数据的学生信息系统。 我正在编写用于添加数据的代码,请告诉我哪里出错了,每当我输入一个卷号时,它仅接受第一个,然后提示``卷号不存在''。但是如果我关闭jar文件并打开再次输入,然后输入不接受的卷,这是第一次。 我已经创建了一个.dat文件来输入数据。

PS我是一个初学者,我刚开始使用Java

import java.io.*;
public class Record
{
  int rollNo, standard;
  String firstName, lastName, address;

  public void read( RandomAccessFile file) throws IOException
  {
    rollNo = file.readInt();
    byte b1[] = new byte[15];
    file.readFully(b1);
    firstName = new String(b1, 0);
    byte b2[] = new byte[15];
    file.readFully(b2);
    lastName = new String(b2, 0);
    standard = file.readInt();
    byte b3[] = new byte[15];
    file.readFully(b3);
    address = new String(b3, 0);
  }

  public void write( RandomAccessFile file) throws IOException
  {
    file.writeInt( rollNo );
    byte b1[] = new byte[15];
    if( firstName != null)
    firstName.getBytes( 0 , firstName.length(), b1, 0);
    file.write(b1);
    byte b2[] = new byte[15];
    if( lastName != null)
    lastName.getBytes( 0, lastName.length(), b2, 0);
    file.write(b2);
    file.writeInt( standard );
    byte b3[] = new byte[15];
    if( lastName != null)
    address.getBytes( 0, address.length(), b3, 0);
    file.write(b3);   
  }
  public int size(){ return 53;}
}


import java.io.*;
import java.awt.*;

public class StudentInformation extends Frame
{
  Button updateButton, newButton, deleteButton, viewButton, done;
  UpdateRec update;
  NewRec newRec;
  DeleteRec deleteRec;
  ViewRec viewRec;
  RandomAccessFile file;
  Record data;

  public StudentInformation()
  {
    super("Student Database");
    try
    {
      file = new RandomAccessFile("credit.dat", "rw");
    }
    catch(IOException e)
    {
      System.err.println(e.toString());
      System.exit(1);
    }
    data = new Record();
    setup();
  } 

  public void setup()
  {
    resize(300, 120);
    setLayout(new GridLayout(3,2));
    updateButton = new Button("Update Record");
    newButton = new Button("New Record");
    deleteButton = new Button("Delete Record");
    viewButton = new Button("View Records");
    done = new Button("Done");
    add(updateButton);
    add(newButton);
    add(deleteButton);
    add(viewButton);
    add(done);
    show();
    update = new UpdateRec(file);
    newRec = new NewRec(file);
    deleteRec = new DeleteRec(file);
    viewRec = new ViewRec(file);
  }

  public boolean action(Event event, Object o)
  {
    if(event.target instanceof Button)
    {
      String current = (String)event.arg;
      if(current.equals("Update Record"))
        update.show();
      else if(current.equals("New Record"))
        newRec.show();
      else if(current.equals("Delete Record"))
        deleteRec.show();
      else if(current.equals("View Records"))
        viewRec.show();
    } 
    return true;
  }

  public boolean handleEvent(Event event)
  {
    if(event.id == Event.WINDOW_DESTROY || event.target == done)
    {
      cleanup();
      hide();
      dispose();
      System.exit(0);
      return true;
    }
    return super.handleEvent(event);
  }

  public void cleanup()
  {
    try
    {
      file.close();
    }
    catch(IOException e)
    {
      System.err.println(e.toString());
      System.exit(1);
    }
  }

  public static void main(String args[])
  {
    StudentInformation teller = new StudentInformation();
  }
}

class NewRec extends Dialog
{
  RandomAccessFile file;
  TextField roll, fname, lname, stnd, addr;
  Button save, cancel;
  Label rollLabel, fnameLabel, lnameLabel, stndLabel, addLabel;
  Record data;
  int rollNo;

  public NewRec(RandomAccessFile f)
  {
    super(new Frame(), "New Record", true);
    resize(300,150);
    setLayout(new GridLayout(6,2));
    file=f;

    roll = new TextField(20);
    rollLabel = new Label("rollNo");
    fname = new TextField(20);
    fnameLabel = new Label("First Name");
    lname = new TextField(20);
    lnameLabel = new Label("Last Name");
    stnd = new TextField(20);
    stndLabel = new Label("Class");
    addr = new TextField(20);
    addLabel = new Label("Address");
    save = new Button("Save Changes");
    cancel = new Button("Cancel");

    add(rollLabel);
    add(roll);
    add(fnameLabel);
    add(fname);
    add(lnameLabel);
    add(lname);
    add(stndLabel);
    add(stnd);
    add(addLabel);
    add(addr);
    add(save);
    add(cancel);

    data = new Record();
  }

  public boolean action(Event event, Object o)
  {
    if( event.target == save)
    {
      rollNo = Integer.parseInt(roll.getText());

      if(rollNo<1)
      {
        roll.setText("Invalid Roll Num");
        return true;
      }
      try
      {
        file.seek((rollNo-1)*data.size());
        data.read(file);
      }
      catch( IOException e)
      {

      }
      if(data.rollNo!=0)
      {
        roll.setText(String.valueOf(data.rollNo) + " already exists");
        fname.setText("");
        lname.setText("");
        stnd.setText("");
        addr.setText("");
      }
      if(data.rollNo==0)
      {
        try
        {
          data.rollNo = rollNo;
          data.lastName = lname.getText();
          data.firstName = fname.getText();
          data.standard = Integer.parseInt(stnd.getText());
          data.address = addr.getText();
          file.seek((rollNo-1)*data.size());
          data.write(file);
        }
        catch( IOException e)
        {
          roll.setText("Error Writing File" + e.toString());
          return true;
        }
        hide();
        clear();
      }
    }

    else if(event.target == cancel)
    {
      hide();
      clear();
    }
    return true;
  }

  private void clear()
  {
    roll.setText("");
    fname.setText("");
    lname.setText("");
    stnd.setText("");
    addr.setText("");
  }
}

另外,当我在打开“新记录”窗口时按取消时,它不会清除文本字段。

我会尽力帮助您。

第一:这是一个代码审查。 您应该改用: https : //codereview.stackexchange.com/

第二:设计问题:

  • 您的代码应使用Java的功能:序列化和反序列化: 什么是对象序列化?

  • 可以在一个文件中随机读写,一个字节接一个字节是可能的,但这是旧的方式,不是很可靠。

什么在您的代码中不起作用:

  • 最主要的是您不重置数据(在写入数据之后以及在输入之前)

  • 以及发生什么情况取决于文件的大小以及之前输入的数据:如果输入了数据15,则文件将从偏移量0到13为空。例如,如果尝试获取10,则可以:因为您得到0。但是,如果尝试获得25,则会得到一个异常(超出文件限制),然后保留先例数据,然后rollNo“已经存在”。

基本解决方案:在每次输入之前清除数据。

我添加了一个try catch,还警告了不良数据

因此,我提出一些意见。 您应该考虑一下。

Voilà

public boolean action(Event event, Object o)
  {
    if( event.target == save)
    {
        // SOLUTION IS HERE
        data=new Record();

          // TRACE
        // PROBLEM HERE: data keeps precedent value
        System.out.println("SAME PLAYER PLAY AGAIN: data.rollNo ACTUALLY:"+data.rollNo);

      rollNo = Integer.parseInt(roll.getText());

      // TRACE
      System.out.println("rollNo ACTUALLY:"+rollNo);

      if(rollNo<1)
      {
        roll.setText("Invalid Roll Num");
        return true;
      }
      try
      {
        file.seek((rollNo-1)*data.size());
        data.read(file);
      }
      catch( IOException e)
      {
          // TRACE
          System.out.println("EXCEPTION IN FILE !");

        // PROBLEM HERE: data have not been defined: then keeps precedent value

      }

      // TRACE
      System.out.println("data.rollNo ACTUALLY:"+data.rollNo);

      if(data.rollNo!=0)
      {
      // TRACE
       System.out.println("ALREADY EXISTS");


        roll.setText(String.valueOf(data.rollNo) + " already exists");
        fname.setText("");
        lname.setText("");
        stnd.setText("");
        addr.setText("");
      }

      if(data.rollNo==0)
      {
          // TRACE
          System.out.println("NOT FOUND");

     try
       {
        try
        {
          data.rollNo = rollNo;
          data.lastName = lname.getText();
          data.firstName = fname.getText();
          data.standard = Integer.parseInt(stnd.getText());
          data.address = addr.getText();
          file.seek((rollNo-1)*data.size());
          data.write(file);

          // TRACE
          System.out.println("WRITE DATA "+rollNo);
        }
        catch( IOException e)
        {
          roll.setText("Error Writing File" + e.toString());
          return true;
        }
      }

     // SOLUTION
     // WARNING: IF bad datas, 
        catch( Exception ex)
        {
            System.err.println("BAD DATAS");

             JOptionPane.showMessageDialog(new JFrame(),  "WARNING: all fields must be filled !", "WARNING",
                        JOptionPane.ERROR_MESSAGE);

          return true;
        }

        hide();

        // TRACE
        System.out.println("CLEAR");

        clear();

        // PROBLEM HERE: data not reset ! see above
      }
    }

    else if(event.target == cancel)
    {
      hide();
      clear();
    }
    return true;
  }

希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM