序列化难度

时间:2014-08-06 08:44:40

标签: java

我在书本和互联网上看得很好,但找不到解决我特定问题的方法。我很担心时间不多了。

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

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

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

我希望在序列化之前对arrayList中的最后一个对象进行去除时,所有值都是相同的。

我不希望任何人发布答案,但如果有人能指出我正确的方向,我可以尝试自己解决。

祝你好运

理查德

PS。交易号是对象中的第一个,中间是余额,学生号是末尾的四个数字。我添加了主类和序列化类,如果有人想看到登录,交易或其他类我也可以发布这些类。

`

    /**
     * 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

0 个答案:

没有答案