该程序将计算用户的摊销表。问题是我的任务需要使用子程序。我完全忘了这一点,关于如何修改它以包含子程序的任何想法?
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);
}
}
}
答案 0 :(得分:0)
我删除了之前的评论,因为我通过阅读相关标签回答了我自己的问题: - )
例如,在您的班级中定义这样的方法:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
然后在类代码的其他位置按名称调用方法,例如
double amount = CalculateInterest(5500, 4.7);
答案 1 :(得分:0)
关于如何修改它以包含子程序的任何想法?
嗯,你最好不要这样做;即在编写代码之前弄清楚方法需要做什么。
您正在做的是表单或代码重构。这是一个非正式的配方。
像Eclipse这样的IDE可以处理大部分的重构手动工作。
然而,真正的技巧是决定分离&#34;肿块&#34;代码到离散任务;即对那些必须阅读/理解您的代码的人来说有意义的方式。这带来了经验。 IDE无法为您做出决定。
(我是否说从一开始就设计/实施这些方法更容易?)