从数组中获取不正确的值

时间:2013-06-12 18:10:54

标签: java

问题是当我为示例1,2和3创建三个帐户时。然后删除2并添加一个新结果,结果为1,3和2,一切正常。当我添加另一个帐户时,结果是1,3,2,3。添加另一个帐户会得到1,3,3,3,4。 这些值存储在一个文本文件中,数组从该文件中读取和写入它们。

问题是我两次获得相同的帐号。也只是让它总是一个增加是不行的,因为我需要它来填补已删除帐户的空白。

无法弄清楚问题,真的很感激一些帮助!

负责的代码:

private int choice;
public String name;
public int accountNr = 1;
public int cash;
public int funds;
private boolean run = true;
private int index = 0;
private int index1 = 0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
ArrayList<Account> acc = new ArrayList<Account>();
ArrayList<TransferHistory> transferHistory = new ArrayList<TransferHistory>();
public int c;
public int amount;
private int c1;
private int size;
ReaderWriter io = new ReaderWriter();
private int account0;
private Account ac;
private int account1;
private int account3;
private int account2;
private int viewAnswer;
private int deleteAnswer;
private String s = "";

public void startMessage() {
    System.out.println("***** Welcome to our bank system *****");
}

public void mainMenu() {
    while (run == true) {
        acc = io.readFromFile();
        Scanner scan = new Scanner(System.in);
        System.out.println("**** Main menu ****");
        System.out.println("1. Create a new account");
        System.out.println("2. Deposit/Withdraw from account");
        System.out.println("3. Transfer money");
        System.out.println("4. View the account properties");
        System.out.println("5. View one account properties");
        System.out.println("6. Delete account");
        System.out.println("7. Show transfer history");
        System.out.println("8. Show transfer history for one account");
        System.out.println("9. Quit");

        try {
            choice = scan.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Please enter valid choice");
        }

        if (choice == 1) {
            addAccount();
        }
        if (choice == 2) {
            transfer();
        }
        if (choice == 3) {
            transferWithin();
        }
        if (choice == 4) {
            view();
        }
        if (choice == 5) {
            viewOne();
        }
        if (choice == 6) {
            delete();
        }
        if (choice == 7) {
            showTransfers();
        }
        if (choice == 8) {
            showOneTransfer();
        }
        if (choice == 9) {
            quit();
        }
    }
}

public void addAccount() {
    System.out.print("Enter your name: ");
    name = scan.next();
    for (int i = 0; i < acc.size(); i++) {
            if(acc.get(i).getAcc() == accountNr) {
                accountNr++;
            }              

    }
    System.out.println("Your account nr is: " + accountNr);
    System.out.print("Enter your starting funds: ");
    try {
        cash = scan.nextInt();
        if(cash < 0){
        System.out.println("Incorrect input!");
        System.out.println(s);
        scan.reset();
        return;                
        }
        index = acc.size();
        acc.add(index, new Account(name, accountNr, cash)); //Add new account object to specified element in acc arraylist
        index = acc.size();
    io.writeToFile(acc);            
    } catch (InputMismatchException e) {
        System.out.println("The scanner couldn´t read your input, use digits next time.");
        System.out.println("The funds for this account has been set to zero, use transfers to adjust");
        scan.reset();
    }

}

public void transfer() {

    System.out.print("Enter account number to withdraw/deposit to: ");
    try {
        account1 = Integer.parseInt(scan.nextLine());
        if(account1 > acc.size() || account1 <= 0){
        System.out.println("Incorrect input!");
        System.out.println(s);
        scan.reset();
        return;                
        }
    } catch (Exception e) {
        System.out.println("Enter a number!");
        scan.reset();
        return;
    }
    System.out.print("Enter a positive number to deposit and negative to withdraw: ");
    try {
        funds = Integer.parseInt(scan.nextLine());
    } catch (Exception e) {
        System.out.println("Enter a number!");
        scan.reset();
        return;
    }

    for (int i = 0; i < acc.size() + 1; i++) {
        if (account1 == i) {
            if (funds > 0) {
                acc.get(account1 - 1).setCash(funds + acc.get(account1 - 1).getCash());
                System.out.println("The amount is changed to " + acc.get(account1 - 1).getCash());
                index1 = transferHistory.size();
                transferHistory.add(index1, new TransferHistory(account1, funds, account1));
                io.writeTransferedToFile(transferHistory);
                index1 = transferHistory.size();
            }
            if (funds < 0 && funds + acc.get(account1 - 1).getCash() > 0) {

                acc.get(account1 - 1).setCash(funds + acc.get(account1 - 1).getCash());
                System.out.println("The amount is changed to " + acc.get(account1 - 1).getCash());
                index1 = transferHistory.size();
                transferHistory.add(index1, new TransferHistory(account1, funds, account1));
                io.writeTransferedToFile(transferHistory);
                index1 = transferHistory.size();
            } else if (acc.get(account1 - 1).getCash() + funds < 0) {
                System.out.println("This transaction is not allowed since the balance will be negative");
            }
        }
    }


    io.writeToFile(acc);
}

public void view() {
    acc = io.readFromFile();
    for (int i = 0; i < acc.size(); i++) {
        System.out.println(s);
        System.out.println("Account name: " + acc.get(i).tempName);
        System.out.println("Account number: " + acc.get(i).tempAccNr);
        System.out.println("Funds: " + acc.get(i).tempCash);
    }
    if (acc.isEmpty()) {
        System.out.println("No accounts to show");
    }

}

public void quit() {
    System.exit(0);
}

private void transferWithin() {
    System.out.print("Enter account you want to transfer from: ");
    try {
        account3 = Integer.parseInt(scan.nextLine());
        if(account3 > acc.size() || account3 <= 0){
        System.out.println("Incorrect input!");
        System.out.println(s);
        scan.reset();
        return;                
        }
    } catch (Exception e) {
        System.out.print("Enter a account number: ");
        scan.reset();
        return;
    }
    System.out.print("Enter amount you want to transfer: ");
    try {
        amount = Integer.parseInt(scan.nextLine());
    } catch (Exception e) {
        System.out.print("Enter a number: ");
        scan.reset();
        return;
    }
    System.out.print("Enter account you want to transfer to: ");
    try {
        account2 = Integer.parseInt(scan.nextLine());
        if(account2 > acc.size() || account2 <= 0){
        System.out.println("Incorrect input!");
        System.out.println(s);
        scan.reset();
        return;                
        }
    } catch (Exception e) {
        System.out.print("Enter a account number:");
        scan.reset();
        return;
    }
    for (int i = 0; i < acc.size() + 1; i++) {
        if (i == account3) {
            c = acc.get(i - 1).getCash();
            if (c - amount >= 0) {
                acc.get(i - 1).setCash(c - amount);
                System.out.println("Funds in account: " + acc.get(i - 1).getAcc() + " " + acc.get(i - 1).getCash());
                index1 = transferHistory.size();
                transferHistory.add(index1, new TransferHistory(account3, amount, account2));
                io.writeTransferedToFile(transferHistory);
                index1 = transferHistory.size();
            } else if (c - amount < 0) {
                System.out.println("Not enough funds in account");
                mainMenu();
            }
        }
    }
    for (int j = 0; j < acc.size() + 1; j++) {
        if (j == account2) {
            c1 = acc.get(j - 1).getCash();
            acc.get(j - 1).setCash(c1 + amount);
            System.out.println("Funds in account " + acc.get(j - 1).getAcc() + " " + acc.get(j - 1).getCash());
        }
    }
    io.writeToFile(acc);
}

private void viewOne() {
    System.out.println("Enter account number you want to look at");
    try {
        viewAnswer = Integer.parseInt(scan.nextLine());
        if(viewAnswer > acc.size() || viewAnswer <= 0){
        System.out.println("Incorrect input!");
        System.out.println(s);
        scan.reset();
        return;                
        }
    } catch (Exception e) {
        System.out.println("Enter a account number!");
        scan.reset();
        return;
    }

    for (int i = 0; i < acc.size() + 1; i++) {
        if (i == viewAnswer) {
            System.out.println("Account name: " + acc.get(i - 1).getName());
            System.out.println("Account nr: " + acc.get(i - 1).getAcc());
            System.out.println("Funds: " + acc.get(i - 1).getCash());
        }
    }
}

private void delete() {
    System.out.print("Enter account you want to delete: ");
    try {
        deleteAnswer = Integer.parseInt(scan.nextLine());
        if(deleteAnswer > acc.size() || deleteAnswer < 0){
        System.out.println("Incorrect input!");
        System.out.println(s);
        scan.reset();
        return;                
        }
    } catch (Exception e) {
        System.out.println("Enter a account number!");
        scan.reset();
        return;
    }
    for (int i = 0; i < acc.size(); i++) {
        if (acc.get(i).getAcc() == deleteAnswer) {
            acc.remove(i);
            io.writeToFile(acc);
        }

    }
}

private void showTransfers() {
    transferHistory = io.readTransferedFromFile();
    System.out.println(s);
    System.out.println("***Transactions***");
    System.out.println(s);
    for (int i = 0; i < transferHistory.size(); i++) {
        int t = transferHistory.get(i).tempFromAccount;
        int t1 = transferHistory.get(i).temptransfered;
        int t2 = transferHistory.get(i).tempToAccount;
        System.out.println("Transfer from: " + t);
        System.out.println("Transfered amount: " + t1);
        System.out.println("Transfered to: " + t2);
        System.out.println(s);
    }
}

private void showOneTransfer() {
    transferHistory = io.readTransferedFromFile();
    System.out.println(s);
    System.out.println("***Transactions***");
    System.out.println(s);
    System.out.print("Enter account nr: ");
    int z = scan.nextInt();
    System.out.println("Transactions made my account nr "+z+":");
    for (int i = 0; i < transferHistory.size(); i++) {
        if(transferHistory.get(i).tempFromAccount == z){
        int t = transferHistory.get(i).tempFromAccount;
        int t1 = transferHistory.get(i).temptransfered;
        int t2 = transferHistory.get(i).tempToAccount;
        System.out.println("Transfer from: " + t);
        System.out.println("Transfered amount: " + t1);
        System.out.println("Transfered to: " + t2);
        System.out.println(s);
        }
    }
}

}

这里我从文件中填充数组:

public ArrayList<Account> readFromFile() {
    FileReader reader = null;
    ArrayList<Account> result = new ArrayList<Account>();
    try {
        reader = new FileReader(new File(text));
        BufferedReader br = new BufferedReader(reader);
        String row = br.readLine();
        while (row != null) {
            String[] splits = row.split(":");
            if (splits.length == 3) {
                int saveNR = Integer.valueOf(splits[1]);
                int saveAmount = Integer.valueOf(splits[2]);
                String saveName = splits[0];
                result.add(new Account(saveName,saveNR,saveAmount));
            } else {
                System.out.println("Error in file format");
            }
            row = br.readLine();
        }

    } catch (Exception e) {
        System.out.println("Error while reading from file");
    } finally {
        try {
            reader.close();
        } catch (IOException ex) {
            System.out.println("Ignore");
        }
        return result;
    }
}

private void delete() {
    System.out.print("Enter account you want to delete: ");
    try {
        deleteAnswer = Integer.parseInt(scan.nextLine());
        if(deleteAnswer > acc.size() || deleteAnswer < 0){
        System.out.println("Incorrect input!");
        System.out.println(s);
        scan.reset();
        return;                
        }
    } catch (Exception e) {
        System.out.println("Enter a account number!");
        scan.reset();
        return;
    }
    for (int i = 0; i < acc.size(); i++) {
        if (acc.get(i).getAcc() == deleteAnswer) {
            acc.remove(i);
            io.writeToFile(acc);
        }

    }
}

2 个答案:

答案 0 :(得分:3)

如果你想要一个计数器,让它成为类中的静态变量,并在需要新值时递增它。类似的东西:

private static int counter = 0;
private static int nextCounter() {
    return ++counter;
}

或者,出于同步原因,请使用

private static AtomicInteger counter = new AtomicInteger();
private static int nextCounter() {
    return counter.incrementAndGet();
}

但是,我建议您不要再考虑填写帐号中的所有空白。通常在数据库工作中,帐号永远不会被重用。您没有正式使用数据库,但您应该以相同的方式工作。重复使用不会给你带来任何好处,并且你的代码总是有可能使新用户17与旧用户混淆17.想象一下美国社会保障管理局将重复使用社会安全号码会发生什么。

顺便提一下,这就是你错误的原因。在代码中:

for (int i = 0; i < acc.size(); i++) {
    if(acc.get(i).getAcc() == accountNr) {
        accountNr++;
    }              
}

假设accountNr从1开始,有3个帐户,并且他们的帐号为2,1,3。在每次循环后,accountNr变为:

1 ⇢ 1⇢ 2 ⇢ 2.

2是现有的accont编号,但您的代码在最后一次检查后将帐号设置为2。

获取第一个未使用的整数

您想要一种方法来获取acc中第一个未使用的整数。这是:

private int firstUnusedId(List<Account> accounts) {
    List<Integer> ids = new ArrayList<>();
    // Foreach loop.
    for(Account account: accounts) {
        ids.add(account.getAcc());
    }
    Collections.sort(ids);
    for (int index = 0; index < ids.size(); ++index) {
        if (ids.get(index) != index + 1) {
            return index + 1;
        }
    }
    return ids.size() + 1;
}

如果ids是2,1,5,那么它们排序为1,2,5。然后循环比较:

index = 0, index + 1 = 1, compare to 1, equal.
index = 1, index + 1 = 2, compare to 2, equal.
index = 2, index + 1 = 3, compare to 5, not equal, return 3.

如果ID为3,2,1,它们将排序为1,2,3,唯一的区别是最后的比较:

index = 2, index + 1 = 3, compare to 3, equal.
return size + 1 = 4.

答案 1 :(得分:0)

您必须分享更多的代码,但是从我看到的内容中预测您正在使用上一个帐户Nr +1创建新帐户,因此,如果您列表中的最后一个帐户为2,则会创建3 ... 4等。请查看您的新帐户并设置accountNr = acc.size+1