/** * LoopEx * * This program demonstrates if/else 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 LoopEx { public static void main(String[] args) { /** DON'T BE CONCERNED WITH THIS SECTION **/ JFrame frame = new JFrame( "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( "Loop Statement\n\n" + "String message = \"\"; //initialize variable\n\n" + "int i = 0;\n\n" + "// guaranteed to execute at least once\n\n" + "do {\n\n" + " message += \"This is the \" + (i+1) + \"x around the loop\\n\";\n\n" + " i++;\n\n" + "} while( i <= 10 );\n\n" + "tA.setText( message );\n\n" + "JOptionPane.showMessageDialog( frame, \"Check it out! I just looped \" + i + \" " + "times!\", \"Loop Example\", JOptionPane.INFORMATION_MESSAGE );\n\n" + "for(int j = 5; j >= 0; j--) {\n\n" + " message += \"Now I gonna backwards. The counter is at \" + j + \"\\n\";\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) { JOptionPane.showMessageDialog( frame, "I'm about to loop like crazy!", "Loop Example", JOptionPane.INFORMATION_MESSAGE ); /***** THIS IS THE SECTION OF INTEREST *****/ String message = ""; //initialize variable int i = 0; // guaranteed to execute at least once do { message += "This is the " + (i+1) + "x around the loop\n"; i++; } while( i <= 10 ); tA.setText( message ); JOptionPane.showMessageDialog( frame, "Check it out! I just looped " + i + " times!", "Loop Example", JOptionPane.INFORMATION_MESSAGE ); for(int j = 5; j >= 0; j--) { message += "Now I gonna backwards. The counter is at " + j + "\n"; } tA.setText( message ); } }