Java 序列化困难

Java 序列化困难,java,Java,我已经很好地阅读了书籍和互联网,但找不到解决我具体问题的方法。我真的很担心,因为时间不多了 我正在为一个帐户编写代码。每个事务(如果是添加或撤消)都是一个对象。特定类别中的添加金额、提取金额、交易编号、余额和总支出等信息是一个对象。每个对象都存储在arrayList中。还有用于登录的代码,因为这最终将成为一个应用程序。它要求用户输入他们的学号(最后4位) 代码运行正常,并在终止时序列化。运行代码后,我可以看到它已经反序列化了文件,因为arrayList中有一个对象列表 我的问题是,当代码运行时,

我已经很好地阅读了书籍和互联网,但找不到解决我具体问题的方法。我真的很担心,因为时间不多了

我正在为一个帐户编写代码。每个事务(如果是添加或撤消)都是一个对象。特定类别中的添加金额、提取金额、交易编号、余额和总支出等信息是一个对象。每个对象都存储在arrayList中。还有用于登录的代码,因为这最终将成为一个应用程序。它要求用户输入他们的学号(最后4位)

代码运行正常,并在终止时序列化。运行代码后,我可以看到它已经反序列化了文件,因为arrayList中有一个对象列表

我的问题是,当代码运行时,学生编号和余额等值为0。而且事务编号不会递增。当代码运行时,它会增加,但在终止时会停止,当代码再次运行时,从1开始

我希望所有值在序列化时都与序列化之前arrayList中最后一个对象中的值相同

我不希望有人贴出答案,但如果有人能给我指出正确的方向,我可以试着自己解决

致意

理查德

P.P.P.事务数是对象中的第一个,中间的平衡和学生的数字在结尾处是四个数字。我已经添加了main类和serialization类,如果有人想查看login、transaction或其他类,我也可以发布它们

`

/**
*由Richard于2014年7月16日创建。
*/
公共类AccountTest实现可序列化{
公共静态扫描仪键盘=新扫描仪(System.in);
//声明一个名为“transactions”的ArrayList,它将保存AccountInfo的实例。
公共静态ArrayList事务=新建ArrayList();
//声明并启动与AccountTest类相关的变量。
私有静态int transactionNum=0;
私人静态双倍存款金额=0;
公共静态双取金额=0;
专用静态双电流平衡=0;
//提示用户提取、添加资金或退出的方法,
//此方法还更新余额和交易编号。
公共静态void addOrSpend(){
do{//do while循环,以确保该方法重复请求用户输入。
System.out.println(“输入1表示存款,输入2表示取款,输入3表示终止:”);
int choice=keyboard.nextInt();
if(choice==1){//还设置交易号和余额的存款选项。
System.out.println(“输入存款金额”);
存款金额=键盘.nextInt();
transactionNum=transactionNum+1;
提款金额=0;
当前余额=当前余额+存款金额;
//System.out.println(“您输入:“+存款金额”);
}//如果
if(choice==2){//同时设置事务数、余额并调用chooseCategory方法的撤消选项。
System.out.println(“输入要提取的金额”);
取款金额=keyboard.nextInt();
transactionNum=transactionNum+1;
存款金额=0;
currentBalance=currentBalance-提款金额;
AccountCategory.chooseCategory();
}//如果
如果(choice==3){//用户选择退出程序。
AccountSerialize.serialize();
System.out.println(“应用程序终止…”);
系统出口(1);
}//如果
AccountInfo acc=new AccountInfo();//创建AccountInfo类的对象
//AccountInfo类中各种方法的设置器,
//这些变量为类的实例初始化变量。
acc.setTransactionNum(transactionNum);
acc.setDepositAmount(存款金额);
acc.设置取款金额(取款金额);
acc.setCurrentBalance(电流平衡);
acc.SET住宿(会计类别住宿);
acc.setTransport(会计类别运输);
acc.setUtilities(AccountCategory.utilities);
acc.setEntertainment(AccountCategory.entertainment);
acc.setEssentials(AccountCategory.essentials);
acc.setStudentNo(AccountLogin.studentNo);
transactions.add(acc);//将每个新的“acc”对象添加到ArrayList“transaction”中。
//System.out.println(“List:+事务”);未使用的print语句,显示用于测试的ArrayList的内容。
Formatter x=new Formatter();//一系列格式化的打印语句,这些语句允许以带标题的表格格式显示信息。
System.out.println(字符串格式(“%-20s%-20s%-20s%-20s%-20s”、“交易编号”、“存款金额”、“取款金额”、“活期余额”);
System.out.println(String.format(“%-20s%-20s%-20s%-20s%-20s”,transactionNum,存款金额,取款金额,当前余额));
System.out.println(字符串格式(“%-20s%-20s%-20s%-20s%-20s%-20s”,“住宿”,“交通”,“实用工具”,“娱乐”,“必需品”));
System.out.println(字符串格式(“%-20s%-20s%-20s%-20s%-20s”),AccountCategory.AccountCategory.transport,AccountCategory.utilities,
AccountCategory.entertainment、AccountCategory.essentials);
}while(transactions.size()>=0);//重复提示用户的do while语句结束。
}
//程序启动和用户登录的主要方法。
    /**
     * Created by Richard on 16/07/2014.
     */
    public class AccountTest implements Serializable {

        public static Scanner keyboard = new Scanner(System.in);
        //Declare an ArrayList called 'transactions' which will hold instances of AccountInfo.
        public static ArrayList transactions = new ArrayList<AccountInfo>();
        //Declare and initiate variables relating to the AccountTest class.
        private static int transactionNum = 0;
        private static double depositAmount = 0;
        public static double withdrawAmount = 0;
        private static double currentBalance = 0;

        // A method which prompts the user to either withdraw, add funds or quit,
        //this method also updates the balance and transaction number.
        public static void addOrSpend() {
            do {//A do while loop to ensure that the method repeatedly asks the user for input.
                System.out.println("Enter a 1 to deposit, 2 to withdraw, 3 to terminate:");
                int choice = keyboard.nextInt();

                if (choice == 1) {//The deposit choice that also sets transaction no. and the balance.
                    System.out.println("Enter an amount to deposit ");
                    depositAmount = keyboard.nextInt();
                    transactionNum = transactionNum + 1;
                    withdrawAmount = 0;
                    currentBalance = currentBalance + depositAmount;
                    //System.out.println("You entered: " + depositAmount);
                }//if

                if (choice == 2) {//The withdraw choice that also sets transaction num, balance and calls chooseCategory method.
                    System.out.println("Enter an amount to withdraw ");
                    withdrawAmount = keyboard.nextInt();
                    transactionNum = transactionNum + 1;
                    depositAmount = 0;
                    currentBalance = currentBalance - withdrawAmount;
                    AccountCategory.chooseCategory();
                }//if

                if (choice == 3) {//User option to quit the program.
                    AccountSerialize.serialize();
                    System.out.println("App terminated...");
                    System.exit(1);
                }//if

                AccountInfo acc = new AccountInfo();//creates an object of the AccountInfo class


                //Setters for the various methods in the AccountInfo class,
                // these initiate variables for instances of the class.

                acc.setTransactionNum(transactionNum);
                acc.setDepositAmount(depositAmount);
                acc.setWithdrawAmount(withdrawAmount);
                acc.setCurrentBalance(currentBalance);
                acc.setAccommodation(AccountCategory.accommodation);
                acc.setTransport(AccountCategory.transport);
                acc.setUtilities(AccountCategory.utilities);
                acc.setEntertainment(AccountCategory.entertainment);
                acc.setEssentials(AccountCategory.essentials);
                acc.setStudentNo(AccountLogin.studentNo);

                transactions.add(acc);//Adds each new 'acc' object to the ArrayList 'transaction'.
                //System.out.println("List:" + transactions);Unused print statement which shows contents of ArrayList for testing.

                Formatter x = new Formatter();//Series of formatted print statements which allow the information to be displayed in tabular format with headings.
                System.out.println(String.format("%-20s %-20s %-20s %-20s ", "Transaction No.", "Deposit amount", "Withdraw amount", "Current balance"));
                System.out.println(String.format("%-20s %-20s %-20s %-20s", transactionNum, depositAmount, withdrawAmount, currentBalance));
                System.out.println(String.format("%-20s %-20s %-20s %-20s %-20s ", "Accommodation", "Transport", "Utilities", "Entertainment", "Essentials"));
                System.out.println(String.format("%-20s %-20s %-20s %-20s %-20s", AccountCategory.accommodation, AccountCategory.transport, AccountCategory.utilities,
                        AccountCategory.entertainment, AccountCategory.essentials));

            } while (transactions.size() >= 0);//End of do while statement that repeatedly prompts the user.
        }

        //Main method from where the program starts and user logs in. Starts with request for user to login.
        // This then allows the user to continue with the program.
        public static void main(String args[]) {
            AccountSerialize.deSerialize();

            System.out.println("Testing to see if student num is saved, login is..." +AccountLogin.studentNo );
            System.out.println("Testing to see if balance is saved, balance is..." +currentBalance );
            if (AccountLogin.studentNo == 0)
            {
                AccountLogin.numberSave();
            }
            else
            {
                AccountLogin.login();
            }

        }//main
    }//class AccountTest


    import java.io.*;
    import java.util.ArrayList;
    import java.util.List;

    /**
     * Created by Richard on 24/07/2014.
     */
    public class AccountSerialize {

        public static String filename = "budgetApp.bin";
        public static String tmp;

        public static void serialize() {
            try {
                FileOutputStream fos = new FileOutputStream("budgetApp.bin");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(AccountTest.transactions);
                oos.close();
                fos.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            System.out.println("Done writing");
        }//serialize()

       public static void deSerialize(){
            try
            {
                FileInputStream fis = new FileInputStream("budgetApp.bin");
                ObjectInputStream ois = new ObjectInputStream(fis);
                AccountTest.transactions = (ArrayList) ois.readObject();
                ois.close();
                fis.close();
            }catch(IOException ioe){
                ioe.printStackTrace();
                return;
            }catch(ClassNotFoundException c){
                System.out.println("Class not found");
                c.printStackTrace();
                return;
            }
            for( Object tmp:AccountTest.transactions){
                System.out.println(tmp);
            }

        }//deSerialize()
    }//class

import java.util.Scanner;

/**
 * Created by Richard on 22/07/2014.
 */
public class AccountCategory {

    static Scanner keyboard = new Scanner(System.in);

    //Declare and initiate variable to be used in this class.
    public static double accommodation = 0;
    public static double transport = 0;
    public static double utilities = 0;
    public static double entertainment = 0;
    public static double essentials = 0;

    //A method which prints a set of spending category choices and asks the user to choose.
    //Also updates each category variable with the total amount spent in that category
    public static void chooseCategory() {

        System.out.println("Please choose a category of spending, enter corresponding number");
        System.out.println("1:\tAccommodation \n2:\tTransport \n3:\tUtilities \n4:\tEntertainment " +
                "\n5:\tEssentials ");

        double choice = keyboard.nextInt();//User input.

        if (choice == 1) {
            accommodation = accommodation + AccountTest.withdrawAmount;
        }//if
        if (choice == 2) {
            transport = transport + AccountTest.withdrawAmount;
        }//if
        if (choice == 3) {
            utilities = utilities + AccountTest.withdrawAmount;
        }//if
        if (choice == 4) {
            entertainment = entertainment + AccountTest.withdrawAmount;
        }//if
        if (choice == 5) {
            essentials = essentials + AccountTest.withdrawAmount;
        }//if

    }//chooseCategory

}//Class AccountCategory


import java.io.Serializable;
import java.util.Scanner;

/**
 * Created by Richard on 16/07/2014.
 */
public class AccountInfo implements Serializable {

    //Declare variables for types of transaction, balance and categories of spending.
    public int studentNo;
    public int transactionNum;
    public double depositAmount;
    public double withdrawAmount;
    public double currentBalance;
    public double accommodation;
    public double transport;
    public double utilities;
    public double entertainment;
    public double essentials;

    //Series of mutator methods which take and validate the user input from the Test class, setting new variable values
    //for objects of this AccountInfo class.
    public void setStudentNo(int studentNo) {
        this.studentNo = studentNo;
    }

    public void setTransactionNum(int transactionNum) {
        this.transactionNum = transactionNum;
    }

    public void setDepositAmount(double depositAmount) {
        this.depositAmount = depositAmount;
    }

    public void setWithdrawAmount(double withdrawAmount) {
        this.withdrawAmount = withdrawAmount;
    }

    public void setCurrentBalance(double currentBalance) {
        this.currentBalance = currentBalance;
    }

    public void setAccommodation(double accommodation) {
        this.accommodation = accommodation;
    }

    public void setTransport(double transport) {
        this.transport = transport;
    }

    public void setUtilities(double utilities) {
        this.utilities = utilities;
    }

    public void setEntertainment(double entertainment) {
        this.entertainment = entertainment;
    }

    public void setEssentials(double essentials) {
        this.essentials = essentials;
    }

    //A toString method to ensure printed information is user readable
    public String toString() {
        return "AccountInfo[" + transactionNum + "," + depositAmount + "," + withdrawAmount + "," + currentBalance + "," +
                accommodation + "," + transport + "," + utilities + "," + entertainment + "," + essentials + ","+studentNo+"]";
    }//toString

}//class AccountInfo


import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * Created by Richard on 20/07/2014.
 */
public class AccountLogin {

    public static Scanner keyboard = new Scanner(System.in);

    //Declare and initiate variables.
    public static int studentNo=0;
    public static int login=0;

    public static void login() {
        if (studentNo > 0 && Integer.toString(studentNo).length() == 4)//Validation test.
        {
                System.out.println("Log in with last four digits of your student number:");
                 login = keyboard.nextInt();//User input.
            }//if
        if(login==studentNo){
            AccountTest.addOrSpend();//If validated
        }//if
        else{
            enterNoAgain();
        }//else
    }//login()

    //This method checks to see if the user has already entered and saved their details, if not the user is prompted to do so.
    //If the user has already entered their details
    public static void numberSave() {

        if (studentNo == 0) {//Checks to see if student number has already been entered.
            System.out.println("Enter and save the last four digits of your student number, use this to login to the Budgeting app:");
            studentNo = keyboard.nextInt();//User input.

            if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Checks that user input meets requirements.
                System.out.println("You are now logged in:");
                AccountTest.addOrSpend();//Program starts at this point once user input is validated.
            }//if

            else {//If user input does not meet criteria, the following method is called.
                enterNoAgain();
            }//else
        }//if
    }//numberSave()


    // This method takes over if the user has not input valid data.
    // The user is instructed to do so and is given a further 2 opportunities before the program exits
    public static void enterNoAgain() {

        System.out.println("Invalid input: Use 4 numbers only, try again");//Prompt.
        studentNo = keyboard.nextInt();//User input.
        if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Validation test.
            AccountTest.addOrSpend();//If validated
        }//if

        else {
            System.out.println("Last attempt, input last four digits of your student number");//Prompt.
            studentNo = keyboard.nextInt();//User input.
            if (studentNo > 0 && Integer.toString(studentNo).length() == 4) {//Validation test.
                AccountTest.addOrSpend();//If validated
            }//if
            else {
                AccountSerialize.serialize();//Save to file
                System.out.println("You failed to login");
                System.out.println("App terminated...");
                System.exit(1);//Program exits due to invalid user input.
            }//else
        }//else

    }//enterNoAgain()

}//class AccountLogin
 `
AccountTest
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,50.0,0.0,50.0,0.0,0.0,0.0,0.0,0.0,3333]
AccountInfo[1,50.0,0.0,50.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,6666]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,50.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,500.0,0.0,500.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,0.0,0.0,50.0,0.0,0.0,1234]
AccountInfo[1,1000.0,0.0,1000.0,0.0,0.0,0.0,0.0,0.0,1234]
AccountInfo[2,0.0,50.0,950.0,50.0,0.0,0.0,0.0,0.0,1234]
Testing to see if student num is saved, login is...0
Testing to see if balance is saved, balance is...0.0
Enter and save the last four digits of your student number, use this to login to the Budgeting app:
1234
You are now logged in:
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
1
Enter an amount to deposit 
1000
Transaction No.      Deposit amount       Withdraw amount      Current balance      
1                    1000.0               0.0                  1000.0              
Accommodation        Transport            Utilities            Entertainment        Essentials           
0.0                  0.0                  0.0                  0.0                  0.0                 
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
2
Enter an amount to withdraw 
50
Please choose a category of spending, enter corresponding number
1:  Accommodation 
2:  Transport 
3:  Utilities 
4:  Entertainment 
5:  Essentials 
1
Transaction No.      Deposit amount       Withdraw amount      Current balance      
2                    0.0                  50.0                 950.0               
Accommodation        Transport            Utilities            Entertainment        Essentials           
50.0                 0.0                  0.0                  0.0                  0.0                 
Enter a 1 to deposit, 2 to withdraw, 3 to terminate:
3
Done writing
App terminated...

Process finished with exit code 1