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

最初に、アカウント番号を維持するためのテーブルを作成します。ファイルにテキストを書き込んだ後、毎回 を使用して、前のアカウント番号のテーブルを新しいアカウント番号に更新し、アカウント番号の値をインクリメントします。

于 2012-06-09T12:23:15.347 に答える