2016-10-17 119 views
1

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

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

不是递归的,只是一个普通的方法。我只是不知道如何去实现一个方法在我已经创建的代码中。这可能就像为for循环创建一个方法一样简单,但我不知道如何在主要的 – akhg2235

+0

Java中使用它,但是一般算法也可以运行 – akhg2235

回答

0

如何修改这包括子程序任何想法?

那么,你最好是反其道而行之;即在编写代码之前计算出需要的方法。

你在做什么是一种形式或代码重构。这是一个非正式的做法。

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

像Eclipse这样的IDE可以处理重构的大部分手工工作。然而,真正的技巧在于决定将“块”代码分离成离散任务的最佳方式;即对于必须阅读/理解你的代码的人来说有意义的方式。这带有经验。而IDE不能为你做出这些决定。

(并没有我说,这是更易于设计/实施从一开始的方法是什么?)

+0

我绝对同意,我只是没有看到使用这种简单问题的方法。但是,是的,应该在开始时创建方法 – akhg2235

+0

关键是让学生根据方法和调用开始思考,而不是编写包含单一千行“main”方法的应用程序。 –

0

我删除了我以前的评论,因为我回答了我的问题通过阅读:-)

相关变量作为一个例子,在你的类定义了这样的方法:

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

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

double amount = CalculateInterest(5500, 4.7);