我需要使用二维数组作为分配的一部分。
我需要在主方法的开头声明变量,用于行计数器和提供 10 行和 4 列的矩形字符串数组
在计算、格式化和显示每次计算的结果的代码之后,添加将格式化的值作为字符串存储在数组的下一行的代码(您需要使用整数类的 toString 方法来存储年份值) .
我已经声明了一个 10x4 的数组和一个计数器变量,但是我在添加将格式化值作为字符串存储在数组的下一行中的代码时遇到了问题(您需要使用整数类的 toString 方法存储年份值)。
这是我在下面为这个问题(2)编写的代码,它似乎打印了一个空值列表,我如何让我的代码打印表格?在我看来,下面的这段代码是导致问题的代码,它正确吗?我有点困惑。
FutureValueArray[counter][0] = Double.toString(monthlyInvestment);
FutureValueArray[counter][1] = Double.toString(interestRate);
FutureValueArray[counter][2] = Integer.toString(years);
FutureValueArray[counter][3] = Double.toString(futureValue);
/*This is how my table should look like.
Inv/Mo. Rate Years Future Value
$100.00 8.0% 10 $18.416.57
$125.00 8.0% 10 $23,020.71*/
public static void main(String[] args)
{
String[][] FutureValueArray = new String [10][4];
int counter = 0;
// display a welcome message
System.out.println("Welcome to the Future Value Calculator");
System.out.println();
// perform 1 or more calculations
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("DATA ENTRY");
double monthlyInvestment = getDoubleWithinRange(sc,
"Enter monthly investment: ", 0, 1000);
double interestRate = getDoubleWithinRange(sc,
"Enter yearly interest rate: ", 0, 30);
int years = getIntWithinRange(sc,
"Enter number of years: ", 0, 100);
// calculate the future value
double monthlyInterestRate = interestRate/12/100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlyInvestment, monthlyInterestRate, months);
// get the currency and percent formatters
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMinimumFractionDigits(1);
// format the result as a single string
String results =
"Monthly investment:\t"
+ currency.format(monthlyInvestment) + "\n"
+ "Yearly interest rate:\t"
+ percent.format(interestRate/100) + "\n"
+ "Number of years:\t"
+ years + "\n"
+ "Future value:\t\t"
+ currency.format(futureValue) + "\n";
// print the results
System.out.println();
System.out.println("FORMATTED RESULTS");
System.out.println(results);
FutureValueArray[counter][0] = Double.toString(monthlyInvestment);
FutureValueArray[counter][1] = Double.toString(interestRate);
FutureValueArray[counter][2] = Integer.toString(years);
FutureValueArray[counter][3] = Double.toString(futureValue);
for(int i = 0; i < FutureValueArray.length; i++)
{
for (int j = 0; j < FutureValueArray[i].length; j++)
System.out.println(FutureValueArray[i][j] + " ");
System.out.println("\n");
}
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
counter++;
System.out.println();
}
}