首页 > 解决方案 > 我不知道在哪里放置我的第二个 Scanner 关闭,有谁知道我是否需要添加第二个或者我是否需要 if 语句在 while 循环所在的位置?

问题描述

所以,我遇到了资源泄漏,因为我没有关闭扫描仪。我修复了第一个,但在 showTax() 函数中遇到了第二个扫描仪的问题。是否像为第二个 keyboard.close() 找到正确的位置一样简单,还是我需要调整循环并添加 If 语句?

import java.util.Scanner;

public class PropertyTaxCalculator {
    public static void main (String[] args) {
        Scanner keyboard = new Scanner(System.in);

        int lotNumber;

        System.out.println("Enter the property's lot number");
        System.out.print("(or enter 0 to end): ");

        lotNumber = keyboard.nextInt();

            while (lotNumber != 0) {
                showTax();

                System.out.print("Enter the next Property's lot number (or 0 to end): ");

                lotNumber = keyboard.nextInt();
                
            }
    keyboard.close();    
    }

    public static void showTax() {
        Scanner keyboard = new Scanner(System.in);
    
        double propertyValue, tax;

        final double TAX_FACTOR = 0.0065;

        System.out.println("Enter the Property Value: ");
        propertyValue = keyboard.nextDouble();

        tax = propertyValue * TAX_FACTOR;
    
        System.out.println("The property's tax is $" + tax);
   
    }
}

标签: java

解决方案


最好让 Scanner 成为类的字段:

编辑:确保键盘字段是静态的,因为它是从静态方法引用的。

import java.util.Scanner;

public class PropertyTaxCalculator {
    private static Scanner keyboard = new Scanner(System.in);
    public static void main (String[] args) {
        int lotNumber;

        System.out.println("Enter the property's lot number");
        System.out.print("(or enter 0 to end): ");

        lotNumber = keyboard.nextInt();

        while (lotNumber != 0) {
            showTax();

            System.out.print("Enter the next Property's lot number (or 0 to end): ");

            lotNumber = keyboard.nextInt();
            
        }
        keyboard.close();    
}

public static void showTax() {
    double propertyValue, tax;

    final double TAX_FACTOR = 0.0065;

    System.out.println("Enter the Property Value: ");
    propertyValue = keyboard.nextDouble();

    tax = propertyValue * TAX_FACTOR;

    System.out.println("The property's tax is $" + tax);

}

}


推荐阅读