A while loop is really useful when you don’t know the exact number of times you have to repeat

while java

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.

while loop java

IN CODE LANGUAGE

void start () {
	Scanner hackerGivesInput = new Scanner(System.in);
	while(hackerGivesInput.hasNextLine()) {
		System.out.println("Error Bitch");
		break;
	}
	start();
}
  1. So I use the Scanner to get input from my a user.
    Scanner hackerGivesInput = new Scanner(System.in);

    I name it hackerGivesInput because this is a small example, I assume that every input that I will get is from the hacker.

  2. Don’t forget to import the Scanner Class, HOW?
    import java.util.Scanner;
  3. To create an unlimited load of errors when the hacker types something
    while(hackerGivesInput.hasNextLine()) {
    	System.out.println("Error Bitch");
    }

    use scanner method: hasNextLine(); or hasNext();

  4. To do it only when we get input add:
    void start () {
    	Scanner hackerGivesInput = new Scanner(System.in);
    	while(hackerGivesInput.hasNextLine()) {
    		System.out.println("Error Bitch");
    		break;
    	}
    	start();
    }
    1. break;
      1. stops the while loop
    2. start();
      1. restarts, the start method again
  5. even shorter, is directly restart the start method
    void start () {
    	Scanner hackerGivesInput = new Scanner(System.in);
    	while(hackerGivesInput.hasNextLine()) {
    		System.out.println("Error Bitch");
    		start();
    	}
    }

SAME AS FOR-LOOP

In a while-loop, you could do the same thing as we did in the for-loop;

for loop java

Of course it will look different:

void start () {
	int count = 0;
	while (count <= 4) {
		System.out.println("WHAT ARE THOOOSEE!");
		count++;
	}
}

As you can see you have to keep track of the counting to let the loop stop.