通过arraylist循环

时间:2016-02-28 21:34:52

标签: java arraylist

大家好我试图使用4个字母的密码和4个int数字的密码来遍历数组。

到目前为止,我可以创建两个键'但我无法让他们在我所拥有的arraylist上搜索帐户,尽管它的创作。我真的不知道如何解决这个问题,因为唯一的方法似乎只是要求“如果'陈述或转换。

这是我设置代码的地方:

int acctID;
        int depositingAmount;
        //System.out.println("Input your ID and then your password to deposit money.");

        String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");

        acctID = Integer.parseInt(inputID);

        String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");

        // int depositAmount;

        // do {

        for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
        {
            if (acctID == bankAccounts.get(i).getAccountId() && inputPassword == bankAccounts.get(i).getPassword())//If ID and password work are true then it goes in here.
            {

                String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
                        + "input");//An here is where you would be able to spit out how much money to deposit.

                depositingAmount = Integer.parseInt(depositAmount);

                bankAccounts.get(i).deposit(depositingAmount);

                break;

            }
        }

就像你可以看到理论上的循环是假设去了#哦;好吧让我开始浏览列表中的所有帐户,直到我找到你的#34;当它找到它时,嘿,我找到了你的账号,在这里让我给你存款功能&#34;。对不起,如果我试图在这一段中过多地简化它只是因为这个问题令我感到沮丧,因为我知道如果我可以解决这个问题,那么我的项目的其余部分就完成了。我也有一个撤销功能,但基本上是相同的,但在同一个类上玩不同的方法。

编辑:这是构造函数

public  BankAccount() {//ADDED TWO PARAMETERS
        //NO ARGUMENT CONSTRUCTOR
        accountId = (int) (Math.random() * 9000) + 999;
        //RANDBETWEEN
        setAccountBalance(0);
        Random passcode = new Random();
        //char charcs = (char)(passcode.nextInt(26) + 'a');
    //Added string. 
        String chars = "abcdefghijklmnopqrstuvwxyz";
        int length = chars.length();
        for (int i = 0; i < 4; i ++){
            password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
    }

    public  BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
        accountId = (int) (Math.random() * 9000) + 1000;
        setAccountBalance(accountBalance);
        //Random passcode = new Random();
        //password = (String) (passcode.nextInt(26)) + 'a';
        //NEED A VARIABLE TO PASS IN
        //4 Digit password

        String chars = "abcdefghijklmnopqrstuvwxyz";
        int length = chars.length();
        for (int i = 0; i < 4; i ++){
            password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}

    }

这里有吸气剂..

public int getAccountId() {
        return accountId;
    }

public String getPassword() {
        return password;
    }

此处还有我创建的字段..

private int accountId;

    private double accountBalance;

    private static double annualInterestRate = 0.045;

    private static java.util.Date dateCreated = new java.util.Date();

    private String name;

    private String password = "";

这是我对If语句的立场

if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))

我已经看到发布的另一个帖子也有类似的问题,但他们回答的只是放置.equals()是不够的。除非我真的想从银行取出银行账户。

编辑2:整个代码。

import java.util.Random;

public class BankAccount {



    private int accountId;

    private double accountBalance;

    private static double annualInterestRate = 0.045;

    private static java.util.Date dateCreated = new java.util.Date();

    private String name;

    private String password = "";

    public  BankAccount() {//ADDED TWO PARAMETERS
        //NO ARGUMENT CONSTRUCTOR
        accountId = (int) (Math.random() * 9000) + 999;
        //RANDBETWEEN
        setAccountBalance(0);
        Random passcode = new Random();
        //char charcs = (char)(passcode.nextInt(26) + 'a');
    //Added string. 
        String chars = "abcdefghijklmnopqrstuvwxyz";
        int length = chars.length();
        for (int i = 0; i < 4; i ++){
            password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}
    }

    public  BankAccount(double accountBalance) { // ONE ARGUMENT CONSTRUCTOR
        accountId = (int) (Math.random() * 9000) + 1000;
        setAccountBalance(accountBalance);
        //Random passcode = new Random();
        //password = (String) (passcode.nextInt(26)) + 'a';
        //NEED A VARIABLE TO PASS IN
        //4 Digit password

        String chars = "abcdefghijklmnopqrstuvwxyz";
        int length = chars.length();
        for (int i = 0; i < 4; i ++){
            password += chars.split("")[ (int) (Math.random() * (length - 1)) ];}

    }

    public int getAccountId() {
        return accountId;
    }

    public double getAccountBalance() {
        return accountBalance;
    }

    public void setAccountBalance(double accountBalance) {
        this.accountBalance = accountBalance;
    }

    public double getAnnualInterestRate() {
        return annualInterestRate;
    }

    public void setAnnualInterestRate(double annualInterestRate) {
        this.annualInterestRate = annualInterestRate;
    }

    public void withdraw(double amountToWithdraw) {

        if (amountToWithdraw > accountBalance) {
            //putting together withdraw make sure to have a validation to stop ppl from going over.
            System.out.println("Sorry you cannot exceed the amount you have in your balance.");
        }
        else {
        accountBalance = accountBalance - amountToWithdraw;
        }
    }

    public void deposit(double amountToDeposit) {

        if (amountToDeposit < 0) {
            //deposits cannot be negative 
        System.out.println("You cannot deposit a negative amount of dallars.");
        }
        else {
        accountBalance = accountBalance + amountToDeposit;
        }
    }

    public double getMonthlyInterestRate() {

        int MonthsInAYear = 12;//method variable is small BUT just need to get results

        double monthlyInterestRate = annualInterestRate / MonthsInAYear;

        return monthlyInterestRate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String toString(){

        String bankInfo = " Password: " + getPassword() + " Account ID: " + getAccountId();

        return bankInfo;
    }
}



public class CurrentAccount extends BankAccount{
    private static float overdraftLimit = 100;
    CurrentAccount(){
        super();
    }

    public static float getOverdraftLimit() {
        return overdraftLimit;
    }

    // MAKE A SETTER FOR THE OVERDRAFTLIMIT
    public void withdraw(double amountToWithdraw){
        if (amountToWithdraw <= getAccountBalance()+overdraftLimit) {
            setAccountBalance(getAccountBalance() - amountToWithdraw);
        }
        else {
            System.out.println("Error this transaction has been cancelled.");
        }
    }

}



public class SavingsAccount extends BankAccount{

    private static double interest;

    public SavingsAccount (){
        super();
        interest = 0;
    }

    public void addInterest(){

        interest = getAccountBalance() * getMonthlyInterestRate(); //GETTING ZEROS FROM ACCOUNTBALANCE
        //CHANGE getAccountBalance with some other initial payment.
        super.deposit(interest);

    }

    public double getInterest() {
        return interest;
    }

    public void setInterest(float interest) {
        this.interest = interest;
    }
}

public class Bank {
    Scanner input = new Scanner(System.in);
    Scanner Restart = new Scanner(System.in);
    private static ArrayList<BankAccount> bankAccounts; // MADE THIS STATIC

    public Bank() {
        bankAccounts = new ArrayList<BankAccount>();
    }

    public void openAccount() {

        Object[] possibilities = {"Regular Account", "Savings Account", "Checking Account"};

        Object inputValue = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
                    "input", JOptionPane.INFORMATION_MESSAGE, null, possibilities, possibilities [0]);

            if (inputValue.equals("Regular Account")) {
                // Make a regular acct
                String inputName = JOptionPane.showInputDialog(null, "Please input your name");

                BankAccount newBankAccount = new BankAccount();

                newBankAccount.setName(inputName);

                bankAccounts.add(newBankAccount);

                JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
                JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());


            } else if (inputValue.equals("Savings Account")) {
                // Make a savings acct
                String inputNameSavings = JOptionPane.showInputDialog(null, "Please input your name");

                BankAccount newBankAccount = new SavingsAccount();

                newBankAccount.setName(inputNameSavings);

                bankAccounts.add(newBankAccount);

                JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
                JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());

            } else if (inputValue.equals("Checking Account")) {
                // Make a checking acct
                String inputNameChecking = JOptionPane.showInputDialog(null, "Please input your name");

                BankAccount newBankAccount = new CurrentAccount(); 

                newBankAccount.setName(inputNameChecking);

                bankAccounts.add(newBankAccount);

                JOptionPane.showMessageDialog(null, "Account ID: " + newBankAccount.getAccountId());
                JOptionPane.showMessageDialog(null, "Account Password: " + newBankAccount.getPassword());
            }

    }

    public static ArrayList<BankAccount> getBankAccounts() {
        return bankAccounts;//Moving this into the Open.Account?
    }

    public void closeAccount() {

        System.out.println("Hello give me the name of the" + " "
                + "account you would like to close.");

        String userName = input.next();// Gets input for first choice.

        // Ask for account id
        System.out.println("Please input your account ID");
        int userAccountId = input.nextInt();

        for (int i = 0; i < bankAccounts.size(); i++) {
            if (bankAccounts.get(i).getName().equals(userName)
                    && bankAccounts.get(i).getAccountId() == userAccountId) {
                bankAccounts.remove(i);
                System.out.println("Account removed");
            }

        }
        // anyway, you would set the name probably in the constructor function
        // for that particular instantiation of the class
    }

    public void update() {
        // UPDATES MY ACCOUNTS
        for (int i = 0; i < bankAccounts.size(); i++) {

            if (bankAccounts.get(i) instanceof SavingsAccount) {

                ((SavingsAccount) bankAccounts.get(i)).addInterest();
            } else if (bankAccounts.get(i) instanceof CurrentAccount) {

                if (bankAccounts.get(i).getAccountBalance() < 0) {
                    System.out.println("\nThe Account: " + bankAccounts.get(i).getName() + " has been OverDrafted.\n");
                }
            }
        }
    }// ends update

    public void withdraw(){

        System.out.println("Input your ID and then your password to withdraw money.");

         int acctID = input.nextInt();

         int withdrawAmount;

        // do {

        for (int i = 0; i < bankAccounts.size(); i++){

            //input needed.

            if (acctID == bankAccounts.get(i).getAccountId()){

                System.out.println("We have found your account. Please input how much money you would like to withdraw.");

                withdrawAmount = input.nextInt();

                bankAccounts.get(i).withdraw(withdrawAmount);

                break;

            }
                        //  } while (input != 1);
        }
    }

    public void deposit(){
        int acctID;
        int depositingAmount;
        //System.out.println("Input your ID and then your password to deposit money.");

        String inputID = JOptionPane.showInputDialog("Please input your ID to begin depositing money.");

        acctID = Integer.parseInt(inputID);

        String inputPassword = JOptionPane.showInputDialog("Please input your password to verify your account.");

        // int depositAmount;

        // do {

        for (int i = 0; i < bankAccounts.size(); i++)//Loops through accounts in my arraylist.
        {
            if (acctID == bankAccounts.get(i).getAccountId() && inputPassword.equals(bankAccounts.get(i).getPassword()))//If ID and password work are true then it goes in here.
            {

                String depositAmount = JOptionPane.showInputDialog("Please input how much money you want to "
                        + "input");//An here is where you would be able to spit out how much money to deposit.

                depositingAmount = Integer.parseInt(depositAmount);

                bankAccounts.get(i).deposit(depositingAmount);

                break;

            }
        }
    }   
    }

最后我正在上课...

import java.util.ArrayList;
import javax.swing.JOptionPane;

public class TestBankAccount {

    public static void main(String[] args) {


    //  JOptionPane.showMessageDialog(null, "Hello User.");
    Object[] menuPossibilities = {"Create a New Account", "Deposit", "Withdraw", "Display Balance", "Exit"};

    Object menuValues = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
                "input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
    while (!menuValues.equals("Exit")){

        Bank newBank = new Bank();
        // Bank newBank1 = new Bank();
        // Bank newBank2 = new Bank(); Do the same thing as below but switch out
        // bank1 and bank2 as a substitute.
        ArrayList<BankAccount> bankList = newBank.getBankAccounts();

            if (menuValues.equals("Create a New Account")){

                newBank.openAccount();
            }

            else if (menuValues.equals("Deposit")){
                newBank.deposit();
            }
            else if (menuValues.equals("Withdraw")){
                newBank.withdraw();
            }
            else if (menuValues.equals("Display Balace")){
                newBank.deposit();
            }
            else if (menuValues.equals("Exit")){
                System.out.println("Thank you for using our service.");
            }

        menuValues = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
                   "input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);


    }


    }
}

1 个答案:

答案 0 :(得分:0)

使用.equals方法检查字符串是否相等。