/** * SwitchStatementEx * * This program demonstrates switch 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 SwitchStatementEx { public static void main(String[] args) { /** DON'T BE CONCERNED WITH THIS SECTION **/ JFrame frame = new JFrame( "Switch 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( "Switch Statement\n\n" + "switch( grade ) {\n\n" + " case 'A':\n\n" + " message += \"You got an A!\\nYou're gonna get paid(???)!\";\n\n" + " //break;\n\n" + " case 'B':\n\n" + " message += \"You got a B!\\nNot bad!\";\n\n" + " break;\n\n" + " case 'C':\n\n" + " message += \"You got an C!\\nStudy a little harder!\";\n\n" + " break;\n\n" + " default:\n\n" + " message += \"You failed!\\n\"; // message string\n\n" + " if( grade == 'D' ) {\n\n" + " message += \"You need to try harder!\";\n\n" + " } else {\n\n" + " message += \"There's no hope!\";\n\n" + " }\n\n" + "} // end switch\n\n" + "tA.setText( message );\n\n" ); } }); frame.getContentPane().add( codeButton, BorderLayout.SOUTH ); frame.pack(); frame.setVisible(true); testSwitch( frame, textArea ); } public static void testSwitch(JFrame frame, JTextArea tA) { String input = JOptionPane.showInputDialog( frame, "What was your grade on assignment 3?" ); if( input.length() != 1 ) { JOptionPane.showMessageDialog( frame, "Please type one character, 'A', 'B', 'C', 'D' or 'F'!", "Incorrect Info", JOptionPane.ERROR_MESSAGE ); return; } char grade = input.toUpperCase().charAt(0); /***** THIS IS THE SECTION OF INTEREST *****/ String message; switch( grade ) { case 'A': message = "You got an A!\nYou're gonna get paid(???)!"; break; case 'B': message = "You got a B!\nNot bad!"; break; case 'C': message = "You got an C!\nStudy a little more!"; break; default: message = "You failed!\n"; // message string if( grade == 'D' ) { message = "You need to try harder!"; } else { message = "There's no hope!"; } } // end switch tA.setText( message ); } }