1

This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?

public class Summ {

public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables

Scanner stdin = new Scanner (System.in);    //create scanner

System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble();                                            // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble();                                            //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble();                                        //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble();                                            //Stores the length of the loan in months

monthlyinterest = annualinterest/1200;                                      //Calculates the monthly interest

System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance");    //Creates the header
double interest, principal;                                                 //initialize variables
int i;                                                                      

/* for loop prints out the interest, principal, and ending 
 * balance for each month. Works by calculating each, 
 * printing out that month, then calculating the next month,
 * and so on.
 */

for (i = 1; i <= loanlength; i++) {                                 
    interest = monthlyinterest * loanamount;
    principal = monthlypay - interest;
    loanamount = loanamount - principal;
    System.out.println(i + "\t\t" + interest
    + "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
    }
        }
    }
4

2 回答 2

0

关于如何修改它以包含子例程的任何想法?

好吧,你最好反过来做;即在编写代码之前确定方法需要是什么。

您正在做的是表单或代码重构。这是一个非正式的做法。

  1. 检查代码以找到执行特定任务并产生单个结果的部分。如果您能想到一个简单的名称来反映任务的作用,那就是一个好兆头。如果任务对其当前“所在”的局部变量几乎没有依赖关系,这也是一个好兆头。
  2. 编写带有参数的方法声明以传入变量值,并编写结果类型以返回结果。
  3. 将执行该任务的现有语句复制到方法中。
  4. 调整新方法体,以便将旧上下文中对局部变量的引用替换为对相应参数的引用。
  5. 处理返回值。
  6. 将原始语句重写为对新方法的调用。
  7. 重复。

像 Eclipse 这样的 IDE 可以处理大部分手动重构工作。

然而,真正的技能在于决定将“块”代码分成离散任务的最佳方法。即一种对必须阅读/理解您的代码的人有意义的方式。那是有经验的。IDE 无法为您做出这些决定。

(我是否说过从一开始就更容易设计/实现这些方法?)

于 2016-10-17T12:45:49.540 回答
0

当我通过阅读相关标签回答我自己的问题时,我删除了我之前的评论:-)

例如,在您的类中定义这样的方法:

public double CalculateInterest(double loanAmount, double interestRate) {
    //do the calculation here ...
}

然后在您的类代码中的其他地方按名称调用该方法,例如

double amount = CalculateInterest(5500, 4.7);
于 2016-10-17T12:41:28.087 回答