There are several methods for looping around your query:
while (<condition>) { <do something> }
do { <something> } while (<condition>);
for (<init statement>, <condition>, <update statement>) { <do something> }
To demonstrate, you can avoid using one of the above explicit loop constructs using recursion:
mport java.util.Scanner; import java.util.Random; public class Test { public static void ask(int random) { Scanner input = new Scanner(System.in); System.out.print("Pick a number 1-10: "); int number = input.nextInt(); if (number == random) { System.out.println("Good!"); } else if (number > random) { System.out.println("Too Big"); ask(random); } else if (number < random) { System.out.println("Too Small"); ask(random); } } public static void main(String[] args) { Random rand = new Random(); int random = rand.nextInt(10) + 1; ask(random); } }
Here, the ask() method continues to call itself until the final condition is reached (user guessed).
Depending on the skill of the Java virtual machine, this may affect the call stack or not.
mvw source share