0

*如何增加从保存的文本文件中读取的数字?

我正在尝试将从文件读取的帐号添加到数组中,当我向数组添加新数据时,帐号应该是现有帐号的自动增量。我的代码的问题是它可以正常工作,直到我将其保存到文件中。当我重新打开应用程序时,帐号从头开始,即如果保存的帐户号码是 100,101,当我重新打开应用程序时,帐户号码又从 100 开始。请任何人帮助我从文件中读取,然后将其写回文件。*

重新启动应用程序时,数组从头开始。但我只是想知道是否有人可以帮助我找到解决方案

这是我的代码

import java.io.Serializable;

public class Student implements Serializable {
    //--------------------------------------------------------------------------    
    protected static int nextBankID=1000;
    protected int accountNumber;    
    protected String fname;
    protected String lname;
    protected String phone;
  
    //--------------------------------------------------------------------------    
   //constructor
    public Student(String fname, String lname, String phone){

            this.accountNumber = nextBankID++;
            this.fname = fname;
            this.lname = lname;
            this.phone=phone;                 
    }
    //--------------------------------------------------------------------------
    public void setFname(String fname) {
        this.fname = fname;
    }
    //--------------------------------------------------------------------------
    public void setLname(String lname) {
        this.lname = lname;
    }
    //--------------------------------------------------------------------------
    public void setPhone(String phone) {
        this.phone = phone;
    }
    //--------------------------------------------------------------------------
    public int getAccountNumber() {
        return accountNumber;
    }
    //--------------------------------------------------------------------------
    public void setAccountNumber(int accountNumber) {
        this.accountNumber = accountNumber;
    }
     
    //--------------------------------------------------------------------------
    public String getFname() {
        return fname;
    }
    //--------------------------------------------------------------------------
    public String getLname() {
        return lname;
    }
    //--------------------------------------------------------------------------
    public String getPhone() {
        return phone;
    }  
   
    @Override
    public String toString(){
 
        return "\n #Acc\tFirst Name"+"\tLast Name\t#Phone"
        + "\tBalance"+ "\tOverdraft\t\t\n"+accountNumber+""
                + "\t"+fname+"\t"+lname+"\t"+phone; 
    }
   
}


//-------------------------------------------------------
   
import java.io.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;

@SuppressWarnings("unchecked")

public class ReadWrite{
    
    //save stuAccount ArrayList will all stuAccount objects to file
public static void writeAccounts(String fileName,ArrayList<Student> stu) {
        //Create a stream between the program and the file
        try
        {
            FileOutputStream foStream = new FileOutputStream(fileName);
            ObjectOutputStream outStream = new ObjectOutputStream(foStream);

            outStream.writeObject(stu);
            outStream.close();
        }
        catch(FileNotFoundException fnfEx)
        {
              JOptionPane.showMessageDialog(null,fnfEx.getMessage());
        }
        catch(IOException ioE)
        {
               JOptionPane.showMessageDialog(null,ioE.getMessage());
        }   
}   
    
    //read stuAccount ArrayList
 public static ArrayList<Student> readAccounts(String fileName,ArrayList<Student> stu){ //throws IOException
     
     try
    {
    //JOptionPane.showMessageDialog(null, "Enter subject details to display");
            //StudentDriver.createSubject();  //create a subject to store stuAccount objects 
                FileInputStream fiStream = new FileInputStream(fileName);
                ObjectInputStream inStream = new ObjectInputStream(fiStream);

                stu = (ArrayList<Student>)inStream.readObject();
                //© Increment's the stu account with 1
                for (int i=0; i< stu.size(); i++){
                     Object b1 = stu.get(i);
                if (b1 instanceof Student){            
                    Student bAccount = (Student)b1;
                if(bAccount.accountNumber==stu.get(i).getAccountNumber())
                    bAccount.accountNumber=stu.get(i).getAccountNumber();
                    }
               
                }//for the next user entry
                inStream.close();

        }
        catch(ClassNotFoundException cnfEx){
            JOptionPane.showMessageDialog(null,cnfEx.getMessage());
        }       
        catch(FileNotFoundException fnfEx){
            JOptionPane.showMessageDialog(null,fnfEx.getMessage());
        }
        catch(IOException ioE){
            JOptionPane.showMessageDialog(null,ioE.getMessage());
        }
     
                JOptionPane.showMessageDialog(null, ""+stu.size()
                        + " stu account(s) found in the database....");
            
    return stu; //return read objects to Driver class   
 }
}


// ----------------------------------------------


import java.awt.Font;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class StudentDriver {
    
public static ArrayList<Student> stu = new ArrayList<>();
private static String fileName = "student.txt";

//------------------------------------------------------------------------------
public static void main(String [] vimal)  throws IOException{

   try{
                    
           stu = ReadWrite.readAccounts(fileName,stu);
                             
       if(stu.isEmpty()){
                JOptionPane.showMessageDialog(null,"No account's found "
                + "in the datbase to load into memory!\n\n");     
       }else{
            JOptionPane.showMessageDialog(null,"File contents "
                    + "read and loaded into memory!\n");
       }
    }
    catch (Exception e) {
                        JOptionPane.showMessageDialog(null,"Error encountered "
                                + "while opening the file"
                                + "\nCould not open file"
                                + "\n" + e.toString());
          } 
   //Initialise Main Menu Choice;              
//------------------------------------------------------------------------------           
    int choice= mainMenu();  
    
    while (choice!=3){

     switch (choice){
            case 1:
                createStudentAccount();//a new account Menu
                break;
            case 2:
                list();//list method            
                break;                  
                
            case -100:          
                    JOptionPane.showMessageDialog(null,"You have selected cancel");
                    break;          
            case -99:           
                    JOptionPane.showMessageDialog(null,"You must select  1-3");
                    break;          
            default:            
                    JOptionPane.showMessageDialog(null,"Not a valid option .Plese"
                                                        + " re-enter your option");
                    break;      
         }//END FO SWITCH STATEMENT 
      choice = mainMenu();
    }//END OF WHILE LOOP
   ReadWrite.writeAccounts(fileName,stu); //save ArrayList contents before exiting
    System.exit(0);                
   }    

//END MAIN , PROGRAM EXITS HERE 


public static int mainMenu(){

    String menu="US COLLEGE\n Main menu\n1.Add New Student\n2. Print All\n3. Exit\n\n";
    
    String userSelection = (String)JOptionPane.showInputDialog(null,menu);
    
        int option = validateSelection(userSelection);
    return  option;
}

//------------------------------------------------------------------------------
//                 CREATE ACCOUNT MENU SELECTION VALIDATION

public static int validateSelection(String createAccount){
    //enter cancel
    if (createAccount==null)
            return-100; 

    //hit enter without entry = zero-length string
    if (createAccount.length()<1)       
            return-99;

    //entered more than one charecter   
    if (createAccount.length()>1)       
            return-101;

    if (createAccount.charAt(0)< 49  || 
                                       createAccount.charAt(0)>51)      
            return-101;
    else    
            return Integer.parseInt(createAccount);
}


 public static void createStudentAccount(){
 
        String acctFirstName,acctLastName,strPhone;
        try{
                   //Account name validation
         acctFirstName = JOptionPane.showInputDialog(null,"Enter your first name");
         acctLastName = JOptionPane.showInputDialog(null,"Enter Your Family Name");
         strPhone =JOptionPane.showInputDialog(null,"Enter Your Phone nuber");
        
       
            stu.add(new Student(acctFirstName,
                                        acctLastName,strPhone));
     }
 catch(Exception e){}             
   }


public static void list(){
    
         String accounts = "";
         String College="\t======== US College ========\n";
         JTextArea output = new JTextArea();
         output.setFont(new Font("Ariel", Font.PLAIN, 12));  
    
if(stu.isEmpty()){
            JOptionPane.showMessageDialog(null,"No account's created yet");
         }
   else{      
         //for each Bank account in  BankAccount ArrayList
         for (Student s1: stu){         
         if(stu.isEmpty()){
                JOptionPane.showMessageDialog(null,"No account's created yet");               
         }else{              
             accounts += s1.toString();          
              } 
         output.setText(College+accounts );         
        }
         JOptionPane.showMessageDialog(null,output);
    }
  }
}
4

1 回答 1

0

First create a table for maintaing account number.After writing text to the file, every time use to update the table of previous account no to new account no by incrementing the value of account no .

于 2012-06-09T12:23:15.347 回答