我正在尝试为另一种方法的兴趣进行计算,并且我知道我必须在main之外创建另一个方法然后将返回结束,但我不知道如何标题这个新方法和如何在那里进行计算。我认为这是令我困惑的while循环。我曾经在一个不同的项目上做过一次这样的事情,所以我知道如何做到这一点,但是这个项目与其他项目不同,我并不是真的理解它。任何帮助都非常受欢迎,因为我已经在这方面工作了很长时间,只是想完成它。提前致谢。
import java.util.Scanner; // This allows for the use of the scanner in the class
public class SavingsAccount // Start of class
{
public static void main(String[]args) // Start of main
{
double P; // These store the amounts that will be used in the accruing interest formula
double i;
double n;
double S = 0;
int timesLooped = 0;
Scanner readConsole = new Scanner(System.in); // This is the scanner
System.out.println("I am a savings account interest calculator."); // Prompts the user for input
System.out.println("How much money have you deposited?");
P = readConsole.nextDouble();
S = P;
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
i = readConsole.nextDouble();
System.out.println("Finally, how long do you plan on having the money in the account?");
n = readConsole.nextDouble();
while (timesLooped <= n)
{
S = S + (P * i);
timesLooped += 1;
}
System.out.println("Your balance in that time span is " + S + "."); // Tells you your ending balance
}
}
答案 0 :(得分:0)
根据您的评论,我认为您想要这个:
private static double addInterest(double S, double P, double i)
{
return S + (P * i);
}
...
public static void main()
{
...
while (timesLooped <= n)
{
S = addInterest(S, P, i);
}
修改强>
我为了好玩而做了一些小改进:
System.out.format
打印结果。以下是代码:
private static double computeCompoundInterest(double principal, double rate,
double years) {
return principal * Math.pow(1 + rate, years);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("I am a savings account interest calculator.");
System.out.println("How much money have you deposited?");
double principal = scanner.nextDouble();
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
double rate = scanner.nextDouble();
System.out.println("How many years will you hold that money in the account?");
double years = scanner.nextDouble();
double total = computeCompoundInterest(principal, rate, years);
System.out.format("Your balance at the end of that period will be %.2f.\n", years, total);
}