gpt4 book ai didi

java - 为什么当直接声明 while(true) 同时 while(isValid=true) 会出现丢失返回错误时,我没有收到丢失的返回语句?

转载 作者:行者123 更新时间:2023-12-01 19:18:54 25 4
gpt4 key购买 nike

我有一个返回整数的方法。我在 while 循环中声明了 boolean 变量。问题是,即使我已经有一个 return 语句,我也会收到一个错误。

“缺少退货声明”

 public static int test() {
boolean isValid = true;
while(isValid) { // isValid will return missing error statement
Scanner s = new Scanner(System.in);
try {
isValid = false;
return s.nextInt();
} catch (InputMismatchException e) {
s.next();
System.out.println("Please enter number through 0 - 9");
}
}
// return 0; no error if not commented
}

同时,如果我将 while 直接声明为 true,我不会丢失返回错误。

“没有错误”
private static int getInt() {
Scanner s = new Scanner(System.in);
System.out.println("Please enter an integer ");
//boolean isValid = true;
while(true) {
try {
return s.nextInt();
} catch(InputMismatchException e) {
// go round again. Read past the end of line in the input first
s.nextLine();
System.out.println("Please enter a number using only the digits 0 to 9 ");
}
}
}

谁能给我解释一下?这有点令人困惑。

最佳答案

编译器不能 100% 确定第一个代码片段,但可以确定第二个。

编译器知道 while(true)除非使用 return,否则循环永远不会停止或 break .它看到只有一个 return在循环内部,所以它知道 while 循环要么没有完成,要么方法返回。这可以。

另一方面,编译器不知道 while(isValid) 何时出现。循环将停止 - 它不知道何时 isValid将是错误的。它不能只检查 isValid = false ?嗯,你可以设置isValid在很多其他方面,不是吗?您可以将其设置为另一个为 false 的变量,您可以将其设置为依赖于多个变量的复杂 boolean 表达式,最终计算结果为 false ...您是说编译器应该静态分析所有这些变量的值吗?这对编译器来说太难了(如果不是不可能的话),所以它不会打扰。

还有一种情况是编译器根本无法处理的。如果 isValid从另一个线程设置?

这就是为什么编译器要求你在最后添加一个 return 语句,以防 while 循环退出而没有点击 return。在while循环内。

关于java - 为什么当直接声明 while(true) 同时 while(isValid=true) 会出现丢失返回错误时,我没有收到丢失的返回语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59384503/

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