资源泄漏输入永远不会关闭 - 我在哪里/何时关闭以及如何关闭?

Dev*_*ski 3 java

我试着关闭它,但我不知道把 input.close(); 放在哪里,我对这一切真的很陌生,问我的教授有失去积分的风险。此外,我不确定我是否应该保留倒数第二个 system.out 每月付款,或者摆脱它。它甚至对我的其余代码有意义吗?

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);
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 5

传统上,您应该将close()调用放在一个finally块中,这样它就会被调用,而不管您在途中遇到任何异常:

Scanner input = new Scanner(System.in);
try {
    // Use input
} finally {
    input.close();     
}
Run Code Online (Sandbox Code Playgroud)

然而,由于 Scanner 是 AutoClosable,Java 7 提供了一个更简洁的语法来做到这一点:

try (Scanner input = new Scanner(System.in)) {
    // Use input
}
Run Code Online (Sandbox Code Playgroud)