所以基本上,我的程序编译正确并且正在工作。但是,当程序计算简单兴趣时,它会显示不正确的值。假设它应该显示470美元,而不是只打印出4.7,对不起的解释感到抱歉,有人能弄明白为什么会发生这种情况吗?
import java.io.*;
import java.util.Scanner;
import java.io.File;
//import java.nio.file.*;
//import java.nio.file.Paths;
public class BankInterest {
public static void main (String [] args) throws IOException
{
/* TASK 1: Declare variables */
Scanner user_input = new Scanner (System.in);
boolean exit;
int accountType;
double balance;
double principal;
// double userInterest;
double r;
double r2;
int year;
String commBank = ("commbank.txt");
String westPac = ("westpac.txt");
/*Check if the expected command line is provided */
if (args.length < 1) {
/* Display the Usage */
System.out.println("Usage: java BankInterest interestRateFileName");
/* Programs quits with an error code */
System.exit(-1);
}
/* TASK 2: Read interest rates from a file */
String filename = (args[0]);
Scanner textReader = new Scanner(new File(filename));
r = textReader.nextDouble();
r2 = textReader.nextDouble();
System.out.println(r);
System.out.println(r2);
/* TASK 3: Take user input - Which Account */
Scanner keyboard = new Scanner (System.in);
System.out.println("Which Account: ");
System.out.println("1 - Savings");
System.out.println("2 - Term Deposits");
accountType = keyboard.nextInt();
if (accountType == 1) {
accountType = 1;
}
else if (accountType == 2) {
accountType = 2;
}
/* TASK 4: Take user input - Principal and Period */
Scanner input = new Scanner (System.in);
System.out.println("Principal: ");
principal = keyboard.nextDouble();
System.out.println("Years: ");
year = keyboard.nextInt();
/* TASK 5: Calculate balance for the chosen account type */
if (accountType == 1) {
double userBalance = principal * Math.pow((1 + r/100), year);
double userInterest = userBalance-principal;
System.out.println("");
System.out.println("The Compound Interest is: " + userBalance);
System.out.println("The total amount of Interest earned:" + userInterest);
}
else if (accountType == 2) {
double userBalance = (principal * r2 * year) / 100;
double userInterest = userBalance-principal;
System.out.println("");
System.out.println("The Simple Interest is: " + userBalance);
System.out.println("The total amount of Interest earned:" + userInterest);
}
}
}
答案 0 :(得分:0)
首先,公式是错误的。正确的是(假设r2
代表%):
double userInterest = (principal * r2 * year) / 100;
double userBalance = principal + userInterest;
答案 1 :(得分:0)
我想这只是因为你给出了利率百分比。我的意思是20%的利率,你的文件中的值是0.20。在你的计算中,你再将它除以100。在您的计算中,将您的兴趣值更改为20或将除法除以100。