簡體   English   中英

我不知道在哪里放置我的第二個 Scanner 關閉,有誰知道我是否需要添加第二個或者我是否需要 if 語句在 while 循環所在的位置?

[英]I can't figure out where to place my second Scanner close, does anyone know if I need add second or do I need an If statement where the while loop is?

所以,我遇到了資源泄漏,因為我沒有關閉掃描儀。 我修復了第一個,但在 showTax() function 中的第二個掃描儀出現問題。 是否像為第二個 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);
   
    }
}

最好讓 Scanner 成為 class 的字段:

編輯:確保鍵盤字段是 static,因為它是從 static 方法引用的。

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);

}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM