我研究过while(true)
过去一个小时循环,但我无法找到有关此循环的答案。
public class Test {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter Integer: ");
int i = GetAnInteger();
System.out.println("You entered: " + i);
}
public static int GetAnInteger() {
while (true) {
try {
return sc.nextInt();
}
catch (InputMismatchException e) {
sc.next();
System.out.println("That's not an Integer, try again: ");
}
}
}
}
问题1:我们知道代码中的所有语句都会被编译器运行。 “while(true)”的目的是确保代码运行并且无限期地运行,方法中的代码将被执行,那么为什么我们首先需要一个 while(true) 循环呢?
问题 2:如果我删除“while(true)”语句,IDE 会要求我创建一个 return 语句或将该方法设置为 void,为什么?在这种情况下“while(true)”如何工作?
Stack Overflow 上的其他帖子主要是在争论为什么 'while(true)' 是好是坏,我对此不感兴趣。我感兴趣的是为什么这段代码在没有“while(true)”的情况下会崩溃,以及我如何知道何时在其他代码中使用“while(true)”?
- 我搜索了 youtube、java Complete Reference 和 Stack Overflow 半个小时,但找不到任何答案。这段代码取自《Java for dummies》一书,它没有解释这个 while(true) 语句的目的。
最佳答案
while(true)
的目的是让它一直运行,直到输入有效并到达return
语句。当它到达return
语句时,它将退出方法/循环这是因为无法保证
try
部分将被执行。如果不是,则该方法需要返回
一些内容。您必须为方法的每个可能的分支包含一个 return 语句。 考虑以下几点:try { //Oh no! InputMismatchException!! return sc.nextInt(); //Goes to catch block } catch (InputMismatchException e) { sc.next(); System.out.println("That's not an Integer, try again: "); //executes catch block } //Uh oh. Now what? What gets returned?
关于java - 与异常处理相关的基本 Java While(true) 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52174492/