Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8046913
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T05:56:30+00:00 2026-06-05T05:56:30+00:00

*How to increment a number read from a saved text file? I’m trying to

  • 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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T05:56:31+00:00Added an answer on June 5, 2026 at 5:56 am

    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 .

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to read a long number from file then increment it and write
Just trying to do a (I thought) simple callout to read a number from
I have code to read in the version number from a make file. VERSION_ID=map(int,re.match(VERSION_ID\s*=\s*(\S+),open(version.mk).read()).group(1).split(.))
I have a starting number to work from which is 0000 and increment it
I am trying to increment a number and update the database and then display
Using Postgres, I'm trying to use AUTO_INCREMENT to number my primary key automatically in
I found a number of ways to automatically increment build numbers with Team build
Would you rather use a version number (that will increment) or a timestamp to
I'm using SimpleXMLElement to read xml returned from a remote server. The results are
I have a string buffer of a huge text file. I have to search

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.