A while loop is really useful when you don’t know the exact number of times you have to repeat
While hacker is trying to hack my computer, give error message.
Theory
A while method will keep going until it reaches the condition to stop.
IN CODE LANGUAGE
- So I use the Scanner to get input from my a user.
I name it hackerGivesInput because this is a small example, I assume that every input that I will get is from the hacker.
- Don’t forget to import the Scanner Class, HOW?
- To create an unlimited load of errors when the hacker types something
use scanner method: hasNextLine(); or hasNext();
- To do it only when we get input add:
- break;
- stops the while loop
- start();
- restarts, the start method again
- break;
- even shorter, is directly restart the start method
SAME AS FOR-LOOP
In a while-loop, you could do the same thing as we did in the for-loop;
Of course it will look different:
As you can see you have to keep track of the counting to let the loop stop.