/** * IfStatementEx * * This program demonstrates loop statements - "The Fibonacci Series. * The Fibonacci series is a sequence of numbers in which each successive number is the sum of the two preceding numbers. * The sequence begins 1, 1, 2, 3, 5, 8, 13, 21, etc. * * @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 FiboEx { public static void main(String[] args) { /** DON'T BE CONCERNED WITH THIS SECTION **/ JFrame frame = new JFrame( "Fibonacci Series 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( "Fibonacci Series\n\n" + "int currentNum, prevNum = 1, prevprevNum = 0; // Initialize all variables\n\n" + "for(int i = 0; i <= 50; i++) {\n\n" + " currentNum = prevNum + prevprevNum; // sum of the two preceding numbers\n\n" + " if( currentNum >= 50 ) // if currentNum >= 50 exit\n" + " break;\n\n" + " message += currentNum + \"\\n\";" + " // Reset variables\n\n" + " prevpreNum = prevNum; // previous number is now the previous to the previous\n\n" + " prevNum = currentNum; // current number is now the previous\n\n" + "}\n\n" + "tA.setText( message ); // Output series" ); } }); frame.getContentPane().add( codeButton, BorderLayout.SOUTH ); frame.pack(); frame.setVisible(true); testFibo( frame, textArea ); } public static void testFibo(JFrame frame, JTextArea tA) { JOptionPane.showMessageDialog( frame, "Are you ready for the Fibonacci Series from 1 to 50" ); String message = ""; //initialize a message variable /***** THIS IS THE SECTION OF INTEREST *****/ int currentNum, prevNum = 1, prevprevNum = 0; // Initialize all variables for(int i = 0; i <= 50; ) { currentNum = prevNum + prevprevNum; // sum of the two preceding numbers if( currentNum >= 50 ) // if currentNum >= 50 exit break; message += currentNum + "\n"; // Reset variables prevprevNum = prevNum; // previous number is now the previous to the previous prevNum = currentNum; // current number is now the previous i = currentNum; // set iterator to current number } tA.setText( message ); // Output series } }