Conditionals and Loops


Conditionals and Loops

Thus far, we have only written linear. Every line of code we wrote has been executed in-order. Such execution is only useful for fairly small programs. Any sufficiently complex project will require some way to interrupt the linear nature of the program.

One such way to accomplish this is by using a conditional. A conditional allows you to execute code ONLY when the necessary condition is met. Another way to do this is through loops. Loops cause certain blocks of code to get repeated as long as a condition is held.

Boolean Operators

In order to use loops or conditionals, one needs knowledge of boolean operators. These operators are ==, !=, <, >, <=, >=, &&, ||, !, and they only work on primitives. The comparisons always return a boolean (True/False) value.

The following operators only operate on boolean values

When working with more complex entities, such as Java Objects (like String), the Object writer must provide a way to compare the objects. For example, String has an equals(String s) method, which can be used to compare two strings. Example:

	String s = "Hello";
	String t = "Hello";
	boolean cond = s.equals(t);
	//ASSERT: cond holds the value true, since
	//s does equal t.


We will now modify the tip calculator example from the previous lab. Instead of giving the user the option to enter in a tip percentage, will will provide select (radio) buttons for the user to press, and will determine how much tip to provide accordingly. Link to Applet.

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

	public class CondTipCalculator extends Applet implements ActionListener{
	     String goodString = "Good";
	     String averageString = "Average";
	     String badString = "Bad";
	     double goodPercent = .15;
             double averagePercent = .10;
	     double badPercent = .05;
	     //Textfields to get the user input
	     TextField checkAmountText;
	     TextField tipPercentText;

	     //Storage for the numbers
	     double checkAmount = 0.0;
	     double tipPercent = 0.0;
	     Label resultLabel1;
	     Label resultLabel2;
	     //Setup the text boxes
	     public void init(){
                  this.setLayout(new BorderLayout());
                  //North panel for information
		  Panel northPanel = new Panel();
		  //New panels for better formatting
		  Panel centerPanel = new Panel();
		  Panel radioPanel = new Panel();
		  Panel resultPanel = new Panel();
		  centerPanel.setLayout(new BorderLayout());

		  Label checkAmountLabel = new Label("Enter your check amount: ");
		  checkAmountText = new TextField(10);

		  Label spacerLabel = new Label("How was your service?");
		  centerPanel.add(spacerLabel, BorderLayout.NORTH);
		  //Good Button, 15% tip
		  JRadioButton goodButton = new JRadioButton(goodString);
		  //Average Button, 10% tip, default selection
		  JRadioButton averageButton = new JRadioButton(averageString, true);
		  //Bad Button, 5% tip
		  JRadioButton badButton = new JRadioButton(badString);
		  //Add buttons to a group, takes care of selections
		  ButtonGroup group = new ButtonGroup();
		  centerPanel.add(radioPanel, BorderLayout.CENTER);
		  //Add action listeners to the radio buttons
		  resultLabel1 = new Label("Tip Amount: $0.00");
		  resultLabel2 = new Label("Total Bill: $00.00");
		  this.add(northPanel, BorderLayout.NORTH);
		  this.add(centerPanel, BorderLayout.CENTER);
		  this.add(resultPanel, BorderLayout.SOUTH);

             public void actionPerformed(ActionEvent e){
		  checkAmount = Double.parseDouble(checkAmountText.getText());
		  String action = e.getActionCommand();
		       tipPercent = goodPercent;    
		  }else if(action.equals(averageString)){
		       tipPercent = averagePercent;
		  }else if(action.equals(badString)){
		       tipPercent = badPercent;
	     public void paint(Graphics g){
		  double tipAmount = checkAmount*tipPercent;  
		  resultLabel1.setText("Tip Amount: " + NumberFormat.getCurrencyInstance().format(tipAmount));
		  resultLabel2.setText("Total Bill: " + NumberFormat.getCurrencyInstance().format(checkAmount+tipAmount));

For now, we will ignore the new JRadioButton code, and focus on the conditional code in actionPerformed().

	String action = e.getActionCommand();
	     tipPercent = goodPercent;    
	}else if(action.equals(averageString)){
	     tipPercent = averagePercent;
	}else if(action.equals(badString)){
	     tipPercent = badPercent;
The first thing done in the above code snippet is we get the command that caused the actionListener to be called (this was defined in init, with setActionCommand()). Then, we set the tipPercent variable depending on which action we detected. So, if the action detected is goodString we set tipPercent to be goodPercent.