我创建了一种方法,可以根据年数计算和显示简单兴趣的值。我想展示所有年份,例如如果年份为5年,我想显示第1,2,3,4,5年的价值
这是我目前的代码
public static String numbers(String method, double principal, double rate, double years) {
double simpleInterest = principal + (principal * (rate / 100) * years);
String interest = "";
for (double digit = 1; digit <= years; digit++) {
if (method.equals("Simple")) {
interest = "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
}
return interest;
}
public static void main(String[] args) {
System.out.print(numbers("Simple", 5000, 5, 5));
}
我的输出是
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
5.0-->$6250.0
但是我希望它也像前几年那样展示
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
1.0-->$5250.0
2.0-->$5500.0
3.0-->$5750.0
4.0-->$6000.0
5.0-->$6250.0
显示前几年我需要做什么?
答案 0 :(得分:0)
您必须每年simpleInterest
计算simpleInterest = principal + (principal * (rate / 100) * digit);
digit
此处year
代表+=
。
并使用interest
运算符将结果连接到return
和concat()
。
您还可以使用字符串public String concat(String s)
方法
以下是此方法的语法:interest = interest.concat(digit + "-->$" + simpleInterest + "\n");
。
您可以像这样使用它:public static String numbers(String method, double principal, double rate, double years) {
double simpleInterest = principal + (principal * (rate / 100) * years);
String interest = "";
System.out.println("Principal: $" + principal + ',' + " Rate: " + rate + "\n"+ "Year Simple Interest Amount\n");
for (double digit = 1; digit <= years; digit++) {
if (method.equals("Simple")) {
simpleInterest = principal + (principal * (rate / 100) * digit);
interest += digit + "-->$" + simpleInterest + "\n";
}
}
return interest;
}
public static void main(String[] args) {
System.out.print(numbers("Simple", 5000, 5, 5));
}
Principal: $5000.0, Rate: 5.0
Year Simple Interest Amount
1.0-->$5250.0
2.0-->$5500.0
3.0-->$5750.0
4.0-->$6000.0
5.0-->$6250.0
<强>输出:强>
while
答案 1 :(得分:0)
ScrollView
如果 if (method.equals("Simple")) {
interest = "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
等于interest
,则在上面的代码中重新分配method
。所以,返回最后一个赋值。
使用"simple"
将新结果连接到+=
,或者只将包含每个结果的interest
作为单个元素返回,然后迭代它。
答案 2 :(得分:0)
public static String numbers(String method,double principal,double rate,double years) {
String interest = "";
for (double digit = 1; digit <= years; digit++)
{
if (method.equals(Simple))
{
double simpleInterest = principal + (principal * (rate / 100) * digit);
interest += "Principal: $" + principal + ',' + " Rate: " + rate + "\n" + "Year Simple Interest Amount\n"
+ digit + "-->$" + simpleInterest;
}
}
return interest;
}