Here are 8 looping Java programs in a Notepad ++ format. They feature the “for loop” and the “while loop”. Some run and some do not and some are infinite loops.

Click here for the code

Class Loops with not run because when using JOptionPane the input arrives as a String and you cannot store a String variable in an integer variable.

Class Loops2 corrects the program above. It parses the String variable into an integer variable using “Integer.parseInt” which is then able to store the value.

The for method has four arguements (parameters separated by semi colons
for (int x = 0; x < times; x++)  {   }
  1.   Declare and initialise x. Zero will be its starting value.
  2.   The condition follows. If true the loop will execute.
  3.   The value of x is increased by one.

Class Loops3 tries to introduce the while loop but it does not run because it wants to use the variable x which has not been declared. The x declaration in the for loop cannot be used because it is local to the for loop only.

Class Loops4 runs. It declares its own version of x and initializes it to zero. The while loop does nothing but the program works. Unfortunately it is also in infinite loop; it never stops running because the condition is never met.

while(x < times)  {   }

The while loop only has one arguement (parameter) – the condition. If true, the loop will execute. Unlike the for loop you have to manually declare the starting variable AND you have to manually increase the value of x so that the condition will eventually become false.

while(x < times)  {   x++ }

Class Loops5 addresses the infinite loop problem of Loops4. The value of x is increased so that the condition is met and the loop terminates.

Class Loop6 has a while loop that successfully runs and prints to the output window.

Class Loop7 tries to introduce another variation of the for loop using the primitive datatype char

for(char x = ‘A’; x < ‘Z’; x++)

This program does not run because it is trying to declare the variable x again. Variable x still exists as it is local to the whole main method and therefore cannot be declared again.

Class Loops8 does run. Instead of trying to use x it has its own loop variable y.

for(char y = ‘A’; y <= ‘Z’; y++)

Here the for loop starts at char capital “A” and loops to “Z”. This works because char is based on the Unicode table and each letter has a value that is one bigger than its predecessor. 

The final output (shortened to save space) looks like this below.