gpt4 book ai didi

java - 简单计算器 - "Resource leak: op is never closed"不关闭扫描仪有什么危害吗?

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:47 24 4
gpt4 key购买 nike

我的问题如下: - 为什么 Eclipse 要我关闭扫描仪?不关闭它们有什么坏处吗?如果我关闭它们,我会获利吗? - 我的代码中是否存在初学者错误? Java 专家会解决什么不同的问题?

我在代码中省略了减法()、乘法()、除法()和模(),因为它们的工作原理几乎与加法()相同。

    import java.util.InputMismatchException;
import java.util.Scanner;

class Calculator {

/**
* @param args
*/
static boolean invalid = true;

static void addition() throws InputMismatchException {
do {
try {
Scanner a = new Scanner(System.in);
Scanner b = new Scanner(System.in);
System.out.print("Enter a number: ");
double a1 = a.nextDouble();
System.out.print("Enter a number to add it to " + a1 + ": ");
double a2 = b.nextDouble();
System.out.println(a1 + " + " + a2 + " = " + (a1 + a2));
invalid = false;
} catch (InputMismatchException e) {
System.out.println("Oops! Please enter only numbers!");
invalid = true;
}
} while (invalid == true);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
int o;
boolean turnOff = false;
do {
System.out.print("Choose from one of the operation options.\n"
+ "Type 1 for addition\n" + " 2 for substraction\n"
+ " 3 for multiplication\n" + " 4 for division\n"
+ " 5 for modulo\n");

Scanner op = new Scanner(System.in);
o = op.nextInt();

switch (o) {
case 1:
addition();
break;
case 2:
subtraction();
break;
case 3:
multiplication();
break;
case 4:
division();
case 5:
modulo();
}
do {
System.out.print("Do you want to do more calculations? (n = no, y = yes) ");
Scanner c = new Scanner(System.in);
char input = c.next().charAt(0);
if (input == 'y') {
turnOff = false;
invalid = false;
} else if (input == 'n') {
turnOff = true;
invalid = false;
} else {
System.out.println("y or n is the only valid input. Try again.");
invalid = true;
}
} while (invalid == true);
} while (turnOff == false);
}
}

最佳答案

通常不关闭AutoCloseable(例如FileInputStream)是一个错误,会导致资源泄漏,因此会出现警告。

但是你在这里问这个问题是对的。假设您按照 Eclipse 的建议并关闭 Scanner a,那么实际上会关闭它所包装的 System.in

在风格上,我很想自始至终使用单个 Scanner 实例,可能作为 Calculator 类中的实例变量。首先,这会避开 Eclipse 警告,但也会(稍微)更高效。

关于java - 简单计算器 - "Resource leak: op is never closed"不关闭扫描仪有什么危害吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49706366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com