在这里完成新手的家伙.我正在研究一个Java程序来提示用户输入3个用于计算未来投资价值的变量.一切都运行得很好,除非是时候把我的数据类型放到一个数组中.
这是输出应该是什么样子:
Year Future Value
1 $1093.80
2 $1196.41
3 $1308.65
...
这就是我的样子:
Year 1
Future Value 1093.81
Year 2
Future Value 1196.41
Year 3
Future Value 1308.65
...
我的年份是一个int值,我的Future值是一个double(四舍五入).我一直坐在这里绞尽脑汁和我能找到的所有论坛都没有成功.每次我将两个值都放入一个数组时,我得到一个关于将两个不同的数据类型放在一起的错误.任何见解将不胜感激.以下是我的完整程序的代码:
import java.util.Scanner;
class investmentValue {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter investment amount: $");
double i = s.nextDouble();
System.out.print("Enter percentage rate: ");
double r = s.nextDouble()/100;
System.out.print("Enter number of years: ");
int y = s.nextInt();
for (y=1; y<=30; y++) {
double f = futureInvestmentValue(i,r,y);
System.out.println("Year " + y);
System.out.println("Future Value " + f);
}
}
public static double futureInvestmentValue (double investmentAmount, double monthlyInterestRate, int years){
double value=1;
value = investmentAmount*Math.pow((1+(monthlyInterestRate/12)),(years * 12));
double roundValue = Math.round(value*100.0)/100.0;
return roundValue;
}
}
解决方法:
一种解决方案是从实现填充功能开始.就像是,
public static String pad(String in, int len) {
StringBuilder sb = new StringBuilder(len);
sb.append(in);
for (int i = in.length(); i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
现在我们可以将它与String.format()结合起来获得美元和美分,对标题和输出行使用一致的printf().得到类似的东西,
// Print the header.
System.out.printf("%s %s%n", pad("Year", 12), "Future Value");
for (int y = 1; y <= 30; y++) {
String year = pad(String.valueOf(y), 13); //
String fv = String.format("$%.2f", futureInvestmentValue(i,r,y));
System.out.printf("%s %s%n", year, fv);
}
标签:java,arrays,concatenation,type-conversion
来源: https://codeday.me/bug/20190830/1768471.html