如何简化以下课程

时间:2015-02-11 20:02:47

标签: java simplify

嗨,我是编程新手,我想知道如何简化以下代码。有没有办法可以设置一个变化,而不是设置第1-6个月?

double RATE;
double SAVING; 
double MONTH1;
double MONTH2;
double MONTH3;
double MONTH4;
double MONTH5;
double MONTH6;

System.out.print("Enter the monthly saving amount: ");
SAVING = input.nextDouble();

RATE = 1.00417;

MONTH1 = SAVING * RATE;
MONTH2 = (MONTH1 + SAVING) * RATE;
MONTH3 = (MONTH2 + SAVING) * RATE;
MONTH4 = (MONTH3 + SAVING) * RATE;
MONTH5 = (MONTH4 + SAVING) * RATE;
MONTH6 = (MONTH5 + SAVING) * RATE;

System.out.println("After the sixth month, the account value is $" + (float) MONTH6);

1 个答案:

答案 0 :(得分:3)

你在这做什么:

MONTH1 = SAVING * RATE;
MONTH2 = (MONTH1 + SAVING) * RATE;
MONTH3 = (MONTH2 + SAVING) * RATE;
MONTH4 = (MONTH3 + SAVING) * RATE;
MONTH5 = (MONTH4 + SAVING) * RATE;
MONTH6 = (MONTH5 + SAVING) * RATE;

你一遍又一遍地写了几乎相同的东西。

对于类似的重复性任务,循环始终是更好的解决方案。

使用循环,您甚至不需要所有MONTH个变量。以下是使用循环消除重复代码totalMonths个月后计算帐户值的示例:

int accountValue = 0;
int monthNumber = 0;

while (monthNumber < totalMonths) {                // Do what's inside the brackets as long as monthNumber is less than totalMonths.
    accountValue = (accountValue + saving) * rate; // Update the account value with saving and rate.
    monthNumber = monthNumber + 1;                 // Increase monthNumber by one.
}

System.out.println("After " + totalMonths + " months, the account value is $" + accountValue);

在上述代码accountValue结束时,totalMonths个月过后,帐户总值将会有。

这是一个非常简单的例子。试验它并确保你100%理解它。

请注意,我用小写(camelCase编写了我的变量名称,确切地说),因为它是Java中常见的naming convention