Section 4.5. Conditional Logic

   

4.5 Conditional Logic

Conditional logic can be represented in Java much as you would represent it in CFScript. There are if/else constructs as well as switch/case constructs. Let's look at these in turn .

4.5.1 The if Statement

There is little difference between how you write an if/else block in Java from how you write it in CFScript. While the < cfelseif > tag can lead one to believe otherwise , there is no specific elseif statement; instead, you use else if .

4.5.2 Retirement.java

 /* shows use of if/else if, else   * works very much as in <CFSCRIPT>  */ // declare a new class called Retirement class Retirement { // the main method is the start point for program processing // it accepts an array of strings called "args" (arguments)     public static void main(String[] args) { // create a new integer called age // because the argument comes in as a string, // we have to parse it into a corresponding integer value // using the parseInt() method of the Integer wrapper class         int age = Integer.parseInt(args[0]); // print a different statement based on the value of age         if (age < 50) {             System.out.println("You are too young to             retire.");         }         else if (age > 50 && age < 65) {             System.out.println("You should start thinking             about retirement.");         }         else {             System.out.println("How's your golf game?");         }     } } 

The comments in the Retirement.java program explain different aspects of the program such as using the Integer wrapper class. The conditional logic itself is very straightforward and requires no explanation ”based on the value of age , a different statement is printed to the command line.

If you simply compile and run Retirement.java , you will get an error such as this:

 C:\jdk1.4\JavaForCF\chp4>java Retirement  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException         at Retirement.main(Retirement.java:17) 

This tells you that while Java was executing your main method it found itself in a state from which it could not recover. Items in the java.lang package throw an ArrayIndexOutOfBoundsException , which is something you might see often. The corresponding error that you may have seen in ColdFusion tells you "cannot reference array at index [x]." It means that you have made programmatic reference to an array cell that doesn't exist.

Examining the program, the square brackets ( [] ) indicate an array much like they do in ColdFusion. Retirement.java makes reference to a value at index of the args array. This is the array of strings that the main method always can accept as arguments. You can actually call the array whatever you like, but args is often used by convention. For now, it is good to know that you can avoid this error by supplying an age at the command line when you run the program. Just as javac demands as an argument the name of the file you want to compile, our retirement program needs an age to test for. Try running the program again, like this:

 java Retirement 30 

Then try substituting different ages to see the different messages. Of course, a real program should have complete error handling to account for users entering a negative value, a value over 110, a non-numeric value, and so on.

4.5.3 The switch Statement

Switch/case usage is similarly quick to pick up. It has one caveat for programmers used to CFScript, however ”your test condition must be an integral type ( char , int , etc.). The following program demonstrates two key things. First, it shows how similar using Java switches is to using them in ColdFusion. The syntax is identical. It also shows how you need to do a little working around to accommodate the fact that Java will only switch against integral types.

4.5.4 SwitchSuperHero.java

[View full width]
 
[View full width]
/* File: SwitchSuperHero.java Purpose: demonstrates how to switch. Remember that you can only switch against BYTE, graphics/ccc.gif SHORT, INT, or CHAR */ public class SwitchSuperHero { public static void main (String[] args) { //supply the code for your superhero // 101 is Superman // 102 is WonderWoman // 103 is Spidey int Superman = 101; int WonderWoman = 102; int Spidey = 103; int hero = Integer.parseInt(args[0]); switch (hero) { case 101 : System.out.println("He is the man of steel"); break; case 102: System.out.println("She has a magic lasso" + " and an invisible plane"); break; case 103: System.out.println("Spiderman does whatever a spider can"); break; // calling with any other number prints this default: System.out.println("I have no knowledge of that superhero"); } } }

Running and output:

 C:\jdk1.4\JavaForCF\chp4>java SwitchSuperHero 103  Spiderman does whatever a spider can 

4.5.5 SwitchWithConvert.java

 /* same as SwitchWithText, but shows   * how to cast the arg into a char  * so it can be switched against.  * Therefore demos use of the charAt() method.  * Also allows that program may be run without  * an argument being passed by embedding the switch  * in an if/else.  */ public class SwitchWithConvert {     public static void main (String[] args) {      if (args.length > 0) {            char option;        // "option" value from command line arg        // so we need to convert to char        option = args[0].charAt(0);        switch (option) {        case 'h' :            System.out.println("I am the help file...");            break;        case 'v' :            System.out.println("This is the verbose option"                + " that shows you everything as it happens.");            break;        case 'o' :           System.out.println("Currently available options:");           System.out.println("h --prints the Help file");           System.out.println("v --runs in Verbose mode");           System.out.println("o --displays this Option list");            break;         default:            System.out.println("Error: Invalid option.");            }         }         // no args passed         else {             System.out.println("You are runnning the program"                + " without passing arguments.");         }     } } 

4.5.6 SwitchNoBreaks.java

 /*    File: SwitchNoBreaks  Purpose: reminds us that switch requires break stmt or else all of them run this behavior is precisely how CFScripts handle switches */ class SwitchNoBreaks {     public static void main (String[] args) {         // accept an arg from the command line         // remember that args come in as strings         int number = Integer.parseInt(args[0]);         // can only switch against ints         switch (number) {             case 1:                 System.out.println("You chose 1");             case 2:                 System.out.println("You chose 2");             default: System.out.println("I don't have a message about that value.");         }     } } 

Here is the output with the argument 1 supplied:

 C:\jdk1.4\JavaForCF\chp4>java SwitchNoBreaks 1  You chose 1 You chose 2 I don't have a message about that value. 

As you can see, just as in CFScript, not using the break statement causes all of the conditions to run.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net