我需要使用二维数组作为赋值的一部分。
我需要在main方法的开头为行计数器和一个提供10行和4列的矩形字符串数组声明变量
在为每次计算计算,格式化并显示resutls的代码之后,添加将格式化值作为字符串存储在数组的下一行中的代码(您需要使用整数类的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();
}
}
答案 0 :(得分:1)
您的代码似乎没问题。
如果你改变了
for(int i = 0; i < FutureValueArray.length; i++)
要
for(int i = 0; i <= counter; i++)
您不会打印尚未设置的FutureValueArray
行的空值。
此外,您似乎希望在该循环中使用System.out.print()
函数,而不是System.out.println()
函数。