java - 摊销表

标签 java subroutine amortization

该程序将为用户计算摊销表。问题是我的作业需要使用子例程。我完全忘记了这一点,关于如何修改它以包含子例程有什么想法吗?

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);
    }
        }
    }

最佳答案

any ideas on how to modify this to include subroutines?

好吧,你最好反过来做;即在编写代码之前弄清楚需要哪些方法。

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

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

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

然而,真正的技巧是确定将“一大堆”代码分成离散任务的最佳方法;即对于必须阅读/理解您的代码的人来说有意义的方式。这需要经验。 IDE 无法为您做出这些决定。

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

关于java - 摊销表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40085931/

相关文章:

java - 如何解释以下正则表达式?

java - Edhesive 说我的程序未通过所有测试

java - Launch4J - 主 jar,所有依赖到一个 exe

function - Haskell 程序的基本结构

Java编译器告诉我我还没有初始化变量 "interest"或 "pmt"

java - 我需要查看上传的图片的正确路径是什么?

perl - 如何检查是否使用对象调用方法调用了子例程

perl - 如何在子程序名称中启用点 (.)?

algorithm - 分摊分布(和百分位数)的计算,适用于 App Engine?

excel - 从 Excel 中的多个主体计算 PMT