gpt4 book ai didi

java - while 和 do-while 中的扫描对象

转载 作者:行者123 更新时间:2023-11-30 07:29:49 25 4
gpt4 key购买 nike

我从 github 获得了这段代码,我决定在我的代码中使用,但使用 do-while 语法。原始代码没有错误或警告,但我的代码有。

原版

public static char getChar(){
char input = 0;
Scanner keyIn;
boolean notValid = true;
while(notValid){
keyIn = new Scanner(System.in); //no warning
try{
input = keyIn.nextLine().charAt(0);
notValid = false;
}catch(InputMismatchException e){
System.err.print("Input Error - Non-Character\n");
System.err.print("Enter Again:\n");
}
}
return input;
}

在我的代码中

public static char setOperend(){    
char operand = 0;
Scanner keyIn;
boolean notValid = true;
do{
keyIn = new Scanner(System.in); //warning:Resource leak: 'keyIn' is never closed
try{
operand= keyIn.nextLine().charAt(0);
notValid = false;
}catch(InputMismatchException e){
System.err.print("애러 : 문자가 아닙니다.");
System.err.print("다시 입력하세요.");
}
}while(notValid );
return operand;
}

事实上,原始代码不需要 keyIn.close() (这也让我感到困惑),我想这是因为当 do-while 第一次执行时,编译器知道它在没有任何条件的情况下执行,因此认为它必须关闭,而原始有条件要检查,并且可能不需要关闭(以防条件从未满足)。但他们两个对我来说似乎是一样的。因为原始版本有这行boolean notValid = true;,所以它也应该至少执行一次。

  • 为什么 while 不需要 close(),而 do-while 需要。
  • 有必要close()吗?

最佳答案

正如其他人所指出的,您在第二个示例中收到警告的原因是编译器可以确定循环将至少执行一次,从而创建扫描程序。在第一个版本中,编译器只是注意到,如果变量不为真,则 while 循环可能不会发生(尽管在本例中显然是这样)。

其他人(在我看来是错误的)指出您应该始终关闭扫描程序。当您的扫描程序围绕 System.in 时,这通常不是一个好主意,因为这将关闭 System.in:

When a Scanner is closed, it will close its input source if the source implements the Closeable interface. Oracle Java Documentation - Scanner

System.in is an InputStream ,其中 implements the Closeable interface ,这意味着您将无法再从用户那里收到任何更多输入 - 可能不是您想要的。

至于解决方案,我会执行以下操作:

public static char setOperend(){    
@SuppressWarnings("resource") // We don't want to close System.in
Scanner keyIn = new Scanner(System.in);
boolean notValid = true;
char operand = 0;

do{
try{
operand= keyIn.nextLine().charAt(0);
notValid = false;
}catch(InputMismatchException e){
System.err.print("애러 : 문자가 아닙니다.");
System.err.print("다시 입력하세요.");
}
}while(notValid );

return operand;
}

这会处理警告,而无需在 System.in 上调用 close()。它还解决了代码中的“问题”,即为循环的每次迭代创建一个新的 Scanner 实例,这是不必要的(而且坦率地说相当难看)。

关于java - while 和 do-while 中的扫描对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36320231/

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