java - 我不知道在哪里放置我的第二个 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);
}
}
解决方案
最好让 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);
}
}
推荐阅读
- google-sheets - 如何将未结订单预期接收日期的第一个实例拉到不同的 Google 表中,比较零件清单
- arrays - Julia SharedArrays - 编写非位类型
- sql - 使用 Informix SQL 进行动态透视
- java - pom.xml 用于具有多个主类的单个 jar
- spring - 如果发生异常,如何禁用记录 Kafka 批处理中的所有消息?
- typescript - 递归除法迷宫生成算法不制作连接迷宫
- python - pysnow 0.7.5 - 如何使用 SQL 中的 2 个表进行复杂查询?
- python - 在 Google Chat 中发送提醒的 Google Cloud 函数
- postgresql - 在 liquibase 4.0 的 sqlfile 标签中传递参数
- r - 将函数应用于我的全局环境 R 中的对象