I have researched while(true)
loops for past hour but I was unable to find my answers about this loop.
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: ");
}
}
}
}
Question 1: We know all the statements in the code will run by the compiler. The purpose of 'while(true)' is to make sure the code runs and it runs indefinitely, the code in the method WILL be executed so why do we need a while(true) loop in the first place?
Question 2: If I remove the 'while(true)' statement, the IDE asks me to create a return statement or make the method as void, why? How does 'while(true)' work in this scenario?
Other posts on Stack Overflow were mostly debating why 'while(true)' is bad or good, I am not interested in this. I am interested in why this code breaks down without 'while(true)' and how do I know when to use 'while(true)' in my other codes?
- I searched youtube, java complete reference and stack overflow for past half an hour but couldnt find any answers. This code was taken from "Java for dummies" book and it runs away from explaining the purpose of this while(true) statement.