Java Article 12 - While Loops

In the last article we introduced a basic control structure called a for loop. Another useful control structure for controlling the flow of your program is the while loop. For and while loops are also referred to as condition-controlled loops since a condition (often a variable) controls the execution and the extent of iteration (repeating or looping) of the loop.

The syntax for a while loop is simple:

while (condition)
{
	//block of code to be executed
}

While is often used with a Boolean (a variable type that has either a "true" or "false" value) variable:

boolean myBoolValue = true;

while (myBoolValue)
{
	System.out.println("If this is printing myBoolValue = true");
}

This will continue to loop (iterate) as long as myBoolValue = true. If myBoolValue is set to false then the loop terminates and java begins reading following the closing brace.

Another common trick is to use the "!" operator to indicate false.

boolean myBoolValue = true

while (!myBoolValue)
{
	System.out.println("If this is printing myBoolValue = false");
	//this will not print since myBoolValue is currently true.
}

You can also use a mathematical expression:

while (x <= 20)
{
	System.out.println("If this is printing x is less than or equal to 20. x = " + x );
}

We use concatenation in the example above to show the value of x during each iteration. You can use a while loop similar to if loops by employing some counting:

int x = 0;

while (x <= 10)
{
	System.out.println("x = " + x );
	x++;
}

Here x is evaluated, then printed, then increased by one (incremented). This is repeated until the while condition fails, which in this case is when x is equal to 11.

In today's example we will use a couple of radio buttons to set our program's state and a button to evaluate the state and display some output to a label based on the state. Radio buttons are simple on or off toggle controls handy for setting and displaying a state.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class WhileLoopExample extends JFrame implements ActionListener
{

	boolean safetyState = true;
	int count = 1;
	int numberToCountTo = 0;
	String outputText= "";
	String buttonSelected= "";
	
	//create our controls
	JRadioButton countToFiveButton = new JRadioButton("Count to 5");
	JRadioButton countToTenButton = new JRadioButton("Count to 10");
	JTextPane textPane = new JTextPane();
	JButton runButton = new JButton("Run");
	
	
	//Constructor
	public WhileLoopExample()
	{
		
		//here we set countToFiveButton to selected by default
		countToFiveButton.setSelected(true);
		runButton.setActionCommand("run");
		runButton.addActionListener(this);
		
		
		 // This groups the buttons into a logical group so that only
		 // one button can be selected at a time.
		 
		ButtonGroup group = new ButtonGroup();
		group.add(countToFiveButton);
		group.add(countToTenButton);
        
		//container for our controls
		JPanel panel = new JPanel();

		//Add our controls to the panel
		panel.add(countToFiveButton);
		panel.add(countToTenButton);
		
		panel.add(textPane);
		panel.add(runButton);
		
		//JScrollpane allows for scrolling of our textPane
		JScrollPane scrollPane = new JScrollPane(textPane);
		
		//This makes the JScrollPane always visible:
		scrollPane.setVerticalScrollBarPolicy
		(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		
		panel.add(scrollPane);
		//This sets the JScrollPane's size:
		scrollPane.setPreferredSize(new Dimension(250, 200));
		add(panel);	
	}

	public void actionPerformed(ActionEvent e)
	{
		
		String actionCommand = e.getActionCommand();
			
		if (actionCommand == "run")
		{
			
			 // If the first radio button is selected, 
			 // numberToCountTo is set to 5, and we will count to 
			 // this number in the while loop.
			 
			if(countToFiveButton.isSelected())
			{
				numberToCountTo = 5;
				
				 // getText() gets the text we set for the 
				 // radiobutton in this case its "Count to 5"
				 
				buttonSelected = countToFiveButton.getText();
			}
			
			//If the second radio button is selected:
			if(countToTenButton.isSelected())
			{
				numberToCountTo = 10;
				buttonSelected = countToTenButton.getText();
			}
				
			
			 // Each time the run button is pressed we label 
			 // the output with which radio button was selected
			 
			outputText += buttonSelected 
			+ " radio button selected" + "\n";
				
			//Here is our while loop
			while (count <= numberToCountTo)
			{
				outputText += count+"\n";
				count++;
			}
			
			//here we add some text and new lines 
			//to show our for loop ended.
			outputText += "While loop terminated\n\n";
			//Now we set our textPane's text to our string, 
			//outputText
			textPane.setText(outputText);
			
			 // Count needs to be reset to its starting value or 
			 // else the while loop may not work.
			 
			count = 1;	
		}
	}

	//We talked about the contents of main in article 9
	public static void main(String[] args)
	{	
		WhileLoopExample whileLoopExample = new WhileLoopExample();
		whileLoopExample.setSize(500, 400);
		whileLoopExample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		whileLoopExample.setVisible(true);
	}
}

Again as we mentioned in article 11 we should be using threading when updating GUI's in swing. However that is an advanced topic and will be covered later in this series.