118 Part II: Writing Your Own Java Programs (Web design)

118 Part II: Writing Your Own Java Programs if (verse == 1) { out.println( That s because he has no brain. ); } if (verse == 2) { out.println( That s because he is a pain. ); } if (verse == 3) { out.println( Cause this is the last refrain. ); } But that approach seems wasteful. Why not create a statement that checks the value of versejust once and then takes an action based on the value that it finds? Fortunately, just such a statement exists. It s called a switchstatement. Listing 5-6 has an example of a switchstatement. Listing 5-6: A switch Statement import static java.lang.System.out; import java.util.Scanner; class JustSwitchIt { public static void main(String args[]) { Scanner myScanner = new Scanner(System.in); out.print( Which verse? ); int verse = myScanner.nextInt(); switch (verse) { case 1: out.println( That s because he has no brain. ); break; case 2: out.println( That s because he is a pain. ); break; case 3: out.println( Cause this is the last refrain. ); break; default: out.println( No such verse. Please try again. ); break; } out.println( Ohhhhhhhh. . . . ); } }
We will hook you up with a JSP web hosting at the great rate, check our jsp web hosting, and join us today!!!

Leave a Reply