2016-02-05 81 views
-3

我正在爲課程做一個程序。到目前爲止,我已經完成了1-3,但我不知道如何實現4和5.我一直卡在這一段時間。有兩類必須使用。獲取數組的總數和平均值

  1. 多少銀行賬戶都在銀行

2)創建一個新的數組來保存BankAccounts

3)在一個循環的指定號碼,詢問用戶的銀行賬戶編號和餘額,使用帳號和餘額構造一個BankAccount對象,並將新的BankAccount對象放入數組中

4)用戶輸入所有銀行帳戶後,使用for循環(或每個循環的a )來計算總噸數l賬戶餘額

5)打印計算出的賬戶餘額和平均餘額。

package Hw2; 
import java.util.Scanner; 
import java.util.ArrayList; 

public class BankArrayTester { 
public static void main(String[] args){ 
     Scanner in = new Scanner(System.in); 
     System.out.println("Please enter the number bank accounts:"); 
     int accounts= in.nextInt(); 
     BankAccount [] accountinfo = new BankAccount [accounts]; 
     int c=0; 
     while(c<accounts){ 
      c++; 
     System.out.println("Enter account number for account "+c); 
     int number=in.nextInt(); 
     System.out.println("Enter balance for account "+c); 
     double balance=in.nextDouble(); 
     int a=0; 
     BankAccount numberbalance = new BankAccount(number,balance); 
     accountinfo [a]=numberbalance; 
     double test1; 
     for (int i = 0; i < accountinfo.length; i++) { 
      test1 = accountinfo[a].getBalance(); 
      System.out.println(test1); 
     } 
     } 
    } 
} 

其他類

package Hw2; 
    /** 
    A bank account has a balance that can be changed by 
    deposits and withdrawals. 
    */ 
    public class BankAccount 
    { 
    private double balance; 
    private int accountNumber; 

/** 
    Constructs a bank account with a zero balance. 
*/ 
public BankAccount(int _accountNumber) 
{ 
    balance = 0; 
} 

/** 
    Constructs a bank account with a given balance. 
    @param initialBalance the initial balance 
*/ 
public BankAccount(int _accountNumber, double initialBalance) 
{ 
    accountNumber = _accountNumber; 
    balance = initialBalance; 
} 

/** 
    Deposits money into the bank account. 
    @param amount the amount to deposit 
*/ 
public void deposit(double amount) 
{ 
    double newBalance = balance + amount; 
    balance = newBalance; 
} 

/** 
    Withdraws money from the bank account. 
    @param amount the amount to withdraw 
*/ 
public void withdraw(double amount) 
{ 
    double newBalance = balance - amount; 
    balance = newBalance; 
} 

/** 
    Gets the current balance of the bank account. 
    @return the current balance 
*/ 
public double getBalance() 
{ 
    return balance; 
} 
} 

/** 
    Gets the account number of the bank account. 
    @return the account number 
*/ 
+1

所以。 。 。你有什麼嘗試,沒有奏效? – TangledUpInBlue

+1

它以什麼方式不起作用? –

+0

我試圖讓它輸出所輸入餘額的總額和平均值。我不知道如何去做這件事。我試圖製作一個新的陣列,並將餘額放入其中,但我永遠無法工作。 –

回答

1

用於查找餘額

double sum=0; 
for (int i = 0; i < accountinfo.length; i++) { 
     test1 = accountinfo[i].getBalance(); 
     sum+=test1; 
     System.out.println(test1); 
    } 

的總和要打印總和與平均值

System.out.println("Total ::"+sum); 
System.out.println("Average ::"+sum/accounts); 
+0

我從總和中得到的輸出只是輸入的最後一個帳戶餘額。它不會添加從以前的輸入中輸入的餘額。 –

+0

我編輯了代碼。它現在會工作。 –

0

你需要知道以下如何平均計算(至少)。 如果您將所有元素的總和除以元素的數量,您將獲得平均值。我的提示是使用一個for循環,它會做的伎倆:)