简体   繁体   English

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

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

I am trying to create a student information system which can add, update,view, delete and search data. 我正在尝试创建一个可以添加,更新,查看,删除和搜索数据的学生信息系统。 I am writing the code for add data, please tell me where i am going wrong as everytime i enter a roll no it only accepts the first one and then prompts that 'roll no already exists'.But if I close the jar file and open it again and then enter a roll no it accepts again for the first time. 我正在编写用于添加数据的代码,请告诉我哪里出错了,每当我输入一个卷号时,它仅接受第一个,然后提示``卷号不存在''。但是如果我关闭jar文件并打开再次输入,然后输入不接受的卷,这是第一次。 I have created a .dat file to enter the data. 我已经创建了一个.dat文件来输入数据。

PS I am a beginner and i've just started java 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("");
  }
}

Also when I press cancel when the 'new record' window is opened it doesnt clears the text fields. 另外,当我在打开“新记录”窗口时按取消时,它不会清除文本字段。

I'll try to help you. 我会尽力帮助您。

First: it is rather a code review. 第一:这是一个代码审查。 You should use instead : https://codereview.stackexchange.com/ 您应该改用: https : //codereview.stackexchange.com/

Second: problems of design: 第二:设计问题:

  • your code should use capabilities of java: serialization and deserialization: What is object serialization? 您的代码应使用Java的功能:序列化和反序列化: 什么是对象序列化?

  • read and write at random in a file, byte by byte is possible, but that's the old way, not very reliable. 可以在一个文件中随机读写,一个字节接一个字节是可能的,但这是旧的方式,不是很可靠。

What does not work in your code: 什么在您的代码中不起作用:

  • the principal thing is that you dont reset data (after having written it, and before input) 最主要的是您不重置数据(在写入数据之后以及在输入之前)

  • and what happens depend on the size of your file, and the datas you have entered before: If you have entered data 15, your file will be empty from offset 0 to 13. Then if you try to get 10 for example: it is OK because you get 0. But if you try to get 25, you get an exception (out of the limit of file), then you keep precedent data, then your rollNo "already exists". 以及发生什么情况取决于文件的大小以及之前输入的数据:如果输入了数据15,则文件将从偏移量0到13为空。例如,如果尝试获取10,则可以:因为您得到0。但是,如果尝试获得25,则会得到一个异常(超出文件限制),然后保留先例数据,然后rollNo“已经存在”。

basic solution: to clear data before each input. 基本解决方案:在每次输入之前清除数据。

I have added one try catch also with warning for bad datas 我添加了一个try catch,还警告了不良数据

Therefore, I have make some comments. 因此,我提出一些意见。 You should think about them. 您应该考虑一下。

Voilà : 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;
  }

Hope it helps 希望能帮助到你

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

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