我尝试关闭它,但我不确定将 input.close(); 放在哪里,我对这一切真的很陌生,问我的教授可能会让我失去分数。我也不确定我是否应该保留倒数第二个系统。每月付款是,还是摆脱它。它对我的其余代码有意义吗?
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//Yearly interest rate
System.out.print("Enter annual interest rate, for example 0.5, no percent sign:");
double annualInterestRate = input.nextDouble();
//Monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
//Number of years
System.out.print("Enter number of years, for example 5: ");
int numberOfYears = input.nextInt() ;
//Loan amount
System.out.print("Enter investment amount, for example 145000.95: ");
double loanAmount = input.nextDouble();
//Calculate payments
double monthlyPayment = loanAmount * monthlyInterestRate / (1
- 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12;
System.out.println("The monthly payment is " +
(int) (monthlyPayment * 100) / 100.0);
System.out.println("Accumulated value is " +
(int) (totalPayment * 100) / 100.0);
最佳答案
传统上,您应该将 close()
调用放在 finally
block 中,这样无论您在途中遇到任何异常,它都会被调用:
Scanner input = new Scanner(System.in);
try {
// Use input
} finally {
input.close();
}
但是,由于 Scanner 是可自动关闭的,因此 Java 7 提供了一种更简洁的语法来执行此操作:
try (Scanner input = new Scanner(System.in)) {
// Use input
}
关于java - 资源泄漏输入永远不会关闭 - 我在哪里/何时关闭以及如何关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25921649/