A file named loanBalance.txt contains numeric values that represent the balance
ID: 3584918 • Letter: A
Question
A file named loanBalance.txt contains numeric values that represent the balance of home loans for customers of a bank. The loan balance for each customer is on a separate line within the file. Example data from the file might be similar to: 65340.50 43892.00 38102.95 89820.75 106530.60 Your Java program must
• read the file into an appropriate array – you may assume that the file exists. The array should be sized to store 500 loan balances but keep in mind that the file may not contain 500 loan balances.
• after reading the file into the array calculate and display the average of the loan balances from the array.
• after reading the file into the array determine and display the largest loan balance from the array.
• use appropriate methods and parameter passing.
Explanation / Answer
LoanBalanceTest.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LoanBalanceTest {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "D:\loanBalance.txt";
File file = new File(fileName);
if(file.exists()) {
Scanner scan = new Scanner(file);
double loanAmount[] = new double[500];
int count = 0;
while(scan.hasNextDouble()) {
loanAmount[count++] = scan.nextDouble();
}
System.out.println("The average of the loan balances: "+getAverageLoanAmount(loanAmount, count));
System.out.println("The largest loan balance: "+getMaxLoanAmount(loanAmount, count));
} else {
System.out.println("File does not exist");
}
}
public static double getMaxLoanAmount(double loanAmount[], int n) {
double max = loanAmount[0];
for(int i=0;i<n;i++) {
if(max < loanAmount[i]) {
max = loanAmount[i];
}
}
return max;
}
public static double getAverageLoanAmount(double loanAmount[], int n) {
double sum = 0;
for(int i=0;i<n;i++) {
sum+=loanAmount[i];
}
return sum/n;
}
}
Output:
The average of the loan balances: 68737.36000000002
The largest loan balance: 106530.6
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.