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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25921649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:57:29  来源:igfitidea点击:

Resource leak input is never closed - where/when do i close and how?

java

提问by Devin Wesolowski

I tried closing it but i'm not sure where to put the input.close();, im really new to all this and asking my professors risks me losing points. Also i'm not sure if i should keep the second to last system.out monthly payment is, or get rid of it. Does it even make sense with the rest of my code?

我试着关闭它,但我不知道把 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);

回答by Jean Logeart

Simply use a try-with-resourcesstatement:

只需使用try-with-resources语句:

try (Scanner input = new Scanner(System.in)) {
    // code using input
}

回答by Mureinik

Traditionally, you should put the close()call in a finallyblock so it's called regardless of any exception you'd have on the way:

传统上,您应该将close()调用放在一个finally块中,以便无论您遇到任何异常都会调用它:

Scanner input = new Scanner(System.in);
try {
    // Use input
} finally {
    input.close();     
}

However, since Scanner is AutoClosable, Java 7 offers a cleaner syntax to do this:

但是,由于 Scanner 是 AutoClosable,Java 7 提供了更简洁的语法来执行此操作:

try (Scanner input = new Scanner(System.in)) {
    // Use input
}

回答by Deepak

Just add input.close when you are done using the Scanner class

使用 Scanner 类完成后只需添加 input.close