带有数组的Java银行帐户。麻烦输出三个帐户

时间:2014-11-15 20:14:25

标签: java

新班级

public class NewClass {
    private String accountNumber;
    private String accountName;
    private double balance;

    public NewClass(String nameIn, String numberIn) {
        accountNumber = numberIn;
        accountName = nameIn;
        balance = 0;
    }

    public String getAccountName() {
        return accountName;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public double getBalance() {
        return balance;
    }

    public void deposit(double amountIn) {
        balance = balance + amountIn;
    }

    public boolean withdraw(double amountIn) {
        if (amountIn < 0 && balance < 0) {
            return false;
        } else {
            balance = balance - amountIn;
            return true;
        }
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }
}

主类

public static void main(String[] args) {
    String accountName = "";
    String accountNum = "";
    Scanner sc = new Scanner(System.in);
    boolean IsAccount = false;

    NewClass[] accountList = new NewClass[3];
    accountList[0] = new NewClass(accountName, accountNum);
    accountList[1] = new NewClass(accountName, accountNum);
    accountList[2] = new NewClass(accountName, accountNum);
    int i = 0;
    int count = 3;
    while (i < count) {
        double amount;

        System.out.print("Enter the account name: ");
        accountName = sc.next();
        accountList[i].setAccountName(accountName);
        System.out.println("Enter the account number: ");
        accountNum = sc.next();
        accountList[i].setAccountNumber(accountNum);
        System.out.print("Enter amount to deposit: ");
        amount = sc.nextDouble();
        accountList[i].deposit(amount);
        System.out.print("Enter amount to withdraw: ");
        amount = sc.nextDouble();
        accountList[i].withdraw(amount);
        i++;
    }
    while (i < count) {
        System.out.println(accountList[i].getAccountNumber());
        System.out.println(accountList[i].getAccountName());
        System.out.println(accountList[i].getBalance());
    }
}

我是java编程的新手,我的银行帐户程序出现问题。输出显示三个帐户,每个帐户包含姓名,帐号和余额。我无法表现出来。任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

看起来您不应该在应该打印输出的循环之前将i重置为0,这意味着i==count由于之前的循环而导致,所以永远不会输入打印输出的循环。

以下是您需要解决的问题:

int i = 0; // add this
while (i < count){
    System.out.println(accountList[i].getAccountNumber());
    System.out.println(accountList[i].getAccountName());
    System.out.println(accountList[i].getBalance());
    i++; // add this too
}

当然,您可以使用增强的for循环使代码更加优雅:

for (NewClass account : accountList) {
    System.out.println(account.getAccountNumber());
    System.out.println(account.getAccountName());
    System.out.println(account.getBalance());        
}