0

*How to increment a number read from a saved text file?

I'm trying to add an account Number read from a file to an array and when I add a new data to the array the account number should be auto increment of the existing account number. The problem with my code is that it woks fine until i save it to a file. When I re-open the application the account number starts back from the beginning i.e if the saved acc number is 100,101 when I re-open the application the acc number starts from 100 again. Please can any one Help Me read from the file and then write it back to file.*

The array is starting from the beginning when restart the application.But I was just wondering If any one can help me to find a solution for this

This is my code

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);
    }
  }
}

1 Answer 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 .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.