Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

switchStatements 85

Java 7 adds support for using strings as the test variable in a switch-case
statement. The Commodityclass in Listing 7.2 uses this statement to either
buy or sell an unspecified commodity. The commodity costs $20 when pur-
chased and earns $15 when sold.


Aswitch-casestatement tests the value of a string named command, run-
ning one block if it equals “BUY”and another if it equals “SELL”.


LISTING 7.2 TheCommodityProgram
1: public classCommodity {
2: public static voidmain(String arguments) {
3: String command = “BUY”;
4: int balance = 550;
5: int quantity = 42;
6:
7: switch(command) {
8: case“BUY”:
9: quantity += 5;
10: balance -= 20;
11: break;
12: case“SELL”:
13: quantity -= 5;
14: balance += 15;
15: }
16: System.out.println(“Balance:“ + balance + “\n”
17: + “Quantity: “+ quantity);
18: }
19: }


This application sets the commandstring to “BUY”in line 3. When the
switchis tested, the caseblock in lines 9–11 is run. The quantity of the
commodity increases by 5 and the balance is lowered by $20.


You might encounter an error when writing this program that prevents it
from being compiled and run. NetBeans might not be configured to
employ features of the language introduced in Java 7. If you use a string in
a switchstatement, you might see a red alert icon to the left of the source
code editor pane on line 7. The error message could be “strings in switch
are not supported,” which indicates that some configuration is needed.


Java 7 features are enabled on a project-by-project basis in NetBeans.
Follow these steps to do this:



  1. In the Projects pane, right-click the Java24 item (or whatever you
    named your project) and click Properties from the pop-up menu. The
    Project Properties dialog opens.

Free download pdf