/** * WhileLoopEx * * This program demonstrates while loops structures. * * @author Brad Rippe */ import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Container; import javax.swing.UIManager; public class WhileLoopEx { public static void main(String[] args) { /** DON'T BE CONCERNED WITH THIS SECTION **/ JFrame frame = new JFrame( "While Loop Demo" ); try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { } frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); final JTextArea textArea = new JTextArea( 35, 35 ); JScrollPane scrollPane = new JScrollPane( textArea ); scrollPane.setPreferredSize( new Dimension( 600, 300 ) ); frame.getContentPane().add( scrollPane, BorderLayout.CENTER ); JButton codeButton = new JButton( "Show Code" ); codeButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { textArea.setFont( new Font("Courier", Font.BOLD, 16 ) ); textArea.setText( "While Loop\n\n" + "String message = \"\";\n\n" + "int i = 0;\n\n" + "// Counter-Control\n\n" + "while( i <= 25 ) {\n\n" + " message += \"Just a simple loop on iteration \" + i + \"\\n\";\n\n" + " i++;\n\n" + "}\n\n" + "// Sentinal Control\n\n" + "final int SENTINAL = -1;\n\n" + "String ageString = \"\";\n\n" + "int age = 0;\n\n" + "while( SENTINAL != age ) {\n\n" + " ageString = JOptionPane.showInputDialog( frame, \"How old are you?\" );\n\n" + " age = Integer.parseInt( ageString );\n\n" + " JOptionPane.showMessageDialog( frame, \"I will ask you this until you type -1!\" );\n\n" + "}\n\n" + "tA.setText( message );" ); } }); frame.getContentPane().add( codeButton, BorderLayout.SOUTH ); frame.pack(); frame.setVisible(true); testLoop( frame, textArea ); } public static void testLoop(JFrame frame, JTextArea tA) { /***** THIS IS THE SECTION OF INTEREST *****/ String message = ""; int i = 0; // Counter-Control while( i <= 25 ) { message += "Just a simple loop on iteration " + i + "\n"; i++; } // Sentinal Control final int SENTINAL = -1; String ageString = ""; int age = 0; while( SENTINAL != age ) { ageString = JOptionPane.showInputDialog( frame, "How old are you?" ); age = Integer.parseInt( ageString ); JOptionPane.showMessageDialog( frame, "I will ask you this until you type -1!" ); } tA.setText( message ); } }