我正在上课。到目前为止我已经完成了1-3次,但我无法确定如何实现4和5.我已经坚持了一段时间。必须使用两个类。
2)创建一个新数组以保存指定数量的BankAccounts
3)在循环中,询问用户银行帐号和余额,使用帐号和余额构建BankAccount对象,并将新的BankAccount对象放入数组中
4)用户输入所有银行账户后,使用for循环(或每个循环一次)来计算数组中账户的总余额
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
*/
答案 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);
答案 1 :(得分:0)
你需要知道如何平均计算(至少)。
如果将所有元素的总和除以元素的数量,您将获得平均值。我的建议是使用一个for
循环,它会起作用:)