Repeating an Action with Loops

Một phần của tài liệu sams teach yourselfa java in 24 hours 6th edition (Trang 88 - 104)

ptg7068951 You use ifalong with the condition to test, as in the following statement:

if (account < 0) {

System.out.println(“Account overdrawn; you need a bailout”);

}

Theifstatement checks whether the accountvariable is below 0 by using the less than operator <. If it is, the block within the ifstatement is run, displaying text.

The block only runs if the condition is true. In the preceding example, if theaccountvariable has a value of 0or higher, the printlnstatement is ignored. Note that the condition you test must be surrounded by parenthe- ses, as in (account < 0).

The less-than operator <is one of several different operators you can use with conditional statements.

Less Than and Greater Than Comparisons

In the preceding section, the <operator is used the same way as in math class: as a less-than sign. There also is a greater-than conditional operator

>, which is used in the following statements:

int elephantWeight = 900;

int elephantTotal = 13;

int cleaningExpense = 200;

if (elephantWeight > 780) {

System.out.println(“Elephant too fat for tightrope act”);

}

if (elephantTotal > 12) {

cleaningExpense = cleaningExpense + 150;

}

The first ifstatement tests whether the value of the elephantWeightvari- able is greater than 780. The second ifstatement tests whether the elephantTotalvariable is greater than 12.

If the two preceding statements are used in a program where

elephantWeightis equal to 600 and elephantTotalis equal to 10, the statements within each ifblock are ignored.

You can determine whether something is less than or equal to something else with the <=operator. Here’s an example:

ptg7068951

ifStatements 81

if (account <= 0) {

System.out.println(“You are flat broke”);

}

There’s also a >=operator for greater-than-or-equal-to tests.

Equal and Not Equal Comparisons

Another condition to check in a program is equality. Is a variable equal to a specific value? Is one variable equal to the value of another? These ques- tions can be answered with the==operator, as in the following statements:

if (answer == rightAnswer) {

studentGrade = studentGrade + 10;

}

if (studentGrade == 100) {

System.out.println(“Show off!”);

}

You also can test inequality, whether something is not equal to something else, with the!=operator, as follows:

if (answer != rightAnswer) { score = score - 5;

}

You can use the ==and !=operators with every type of variable except for strings, because strings are objects.

Organizing a Program with Block Statements

Up to this point, the ifstatements in this hour have been accompanied by a block contained within the {and }brackets. (I believe the technical term for these characters is “squiggly bracket marks.”)

Previously, you have seen how block statements are used to mark the beginning and end of the main()block of a Java program. Each statement within the main()block is handled when the program is run.

An ifstatement does not require a block statement. It can occupy a single line, as in this example:

if (account <= 0) System.out.println(“No more money”);

CAUTION

The operator used to conduct equality tests has two equal signs:==. It’s easy to confuse this operator with the =opera- tor, which is used to give a value to a variable. Always use two equal signs in a conditional statement.

ptg7068951 The statement that follows the ifconditional only is executed if the condi-

tional is true.

Listing 7.1 is an example of a Java program with a block statement used to denote the main()block. The block statement begins with the opening bracket {on Line 2 and ends with the closing bracket }on Line 13. Create a new empty Java file called Gamein NetBeans and enter the text in Listing 7.1.

LISTING 7.1 TheGameProgram

1: class Game {

2: public static void main(String[] arguments) { 3: int total = 0;

4: int score = 7;

5: if (score == 7) {

6: System.out.println(“You score a touchdown!”);

7: }

8: if (score == 3) {

9: System.out.println(“You kick a field goal!”);

10: }

11: total = total + score;

12: System.out.println(“Total score: “ + total);

13: } 14: }

When you run the program, the output should resemble Figure 7.1.

FIGURE 7.1

The output of the Gameprogram.

You can use block statements in ifstatements to make the computer do more than one thing if a condition is true. The following is an example of an ifstatement that includes a block statement:

int playerScore = 12000;

int playerLives = 3;

int difficultyLevel = 10;

if (playerScore > 9999) { playerLives++;

System.out.println(“Extra life!”);

difficultyLevel = difficultyLevel + 5;

}

ptg7068951

if-else Statements 83

The brackets are used to group all statements that are part of the ifstate- ment. If the variable playerScoreis greater than 9,999, three things happen:

. The value of the playerLivesvariable increases by one (because the increment operator ++is used).

. The text “Extra life!” is displayed.

. The value of the difficultyLevelvariable is increased by 5.

If the variable playerScoreis not greater than 9,999, nothing happens. All three statements inside the ifstatement block are ignored.

if - else Statements

There are times when you want to do something if a condition is true and something else if the condition is false. You can do this by using the else statement in addition to the ifstatement, as in the following example:

int answer = 17;

int correctAnswer = 13;

if (answer == correctAnswer) { score += 10;

System.out.println(“That’s right. You get 10 points”);

} else { score -= 5;

System.out.println(“Sorry, that’s wrong. You lose 5 points”);

}

The elsestatement does not have a condition listed alongside it, unlike the ifstatement. The elsestatement is matched with the ifstatement that immediately precedes it. You also can use elseto chain several ifstate- ments together, as in the following example:

if (grade == ‘A’) {

System.out.println(“You got an A. Great job!”);

} else if (grade == ‘B’) {

System.out.println(“You got a B. Good work!”);

} else if (grade == ‘C’) {

System.out.println(“You got a C. What went wrong?”);

} else {

System.out.println(“You got an F. You’ll do well in Congress!”);

}

By putting together several different ifand elsestatements in this way, you can handle a variety of conditions. The preceding example sends a spe- cific message to A students, B students, C students, and future legislators.

ptg7068951

switch Statements

The ifand elsestatements are good for situations with two possible con- ditions, but there are times when you have more than two conditions.

With the preceding grade example, you saw that ifand elsestatements can be chained to handle several different conditions.

Another way to do this is with the switchstatement, which can test for a variety of different conditions and respond accordingly. In the following code, the grading example has been rewritten with a switchstatement:

switch (grade) { case ‘A’:

System.out.println(“You got an A. Great job!”);

break;

case ‘B’:

System.out.println(“You got a B. Good work!”);

break;

case ‘C’:

System.out.println(“You got a C. What went wrong?”);

break;

default:

System.out.println(“You got an F. You’ll do well in Congress!”);

}

The first line of the switchstatement specifies the variable that is tested—

in this example, grade. Then, the switchstatement uses the {and }brack- ets to form a block statement.

Each casestatement checks the test variable in the switchstatement against a specific value. The value used in a casestatement can be a char- acter, an integer, or a string. In the preceding example, there are casestate- ments for the characters A, B, and C. Each has one or two statements that follow it. When one of these casestatements matches the variable in switch, the computer handles the statements after the casestatement until it encounters a breakstatement.

For example, if the gradevariable has the value of B, the text “You got a B.

Good work!” is displayed. The next statement is break, so nothing else in the switchstatement is executed. The breakstatement tells the computer to break out of the switchstatement.

The defaultstatement is used as a catch-all if none of the preceding case statements is true. In this example, it occurs if the gradevariable does not equal A, B, or C. You do not have to use a defaultstatement with every switchblock statement you use in your programs. If it is omitted, nothing

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 class Commodity {

2: public static void main(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.

ptg7068951 2. In the Categories pane, click Sources if it is not already selected. The

dialog displays source code properties (see Figure 7.2).

3. In the Source/Binary Format drop-down, choose JDK 7 and click OK.

FIGURE 7.2

Setting up the NetBeans editor to support Java 7.

This sets up the source code editor for all programs in the project to work with Java 7.

When the Commodity program is run, it produces the following output:

Balance: 530 Quantity: 47

The Conditional Operator

The most complicated conditional statement in Java is the ternary operator ?. You can use the ternary operator when you want to assign a value or dis- play a value based on a condition. For example, consider a video game that sets the numberOfEnemiesvariable based on whether the skillLevel variable is greater than 5. One way you can do this is an if-elsestate- ment:

if (skillLevel > 5) { numberOfEnemies = 10;

ptg7068951

Watching the Clock 87

} else {

numberOfEnemies = 5;

}

A shorter way to do this is to use the ternary operator. A ternary expres- sion has five parts:

. The condition to test, surrounded by parentheses, as in (skillLevel

> 5)

. A question mark (?)

. The value to use if the condition is true . A colon (:)

. The value to use if the condition is false

To use the ternary operator to set numberOfEnemiesbased on skillLevel, you could use the following statement:

int numberOfEnemies = (skillLevel > 5) ? 10 : 5;

You also can use the ternary operator to determine what information to display. Consider the example of a program that displays the text “Mr.” or

“Ms.” depending on the value of the gendervariable. Here’s a statement that accomplishes this:

System.out.print( (gender.equals(“male”)) ? “Mr.” : “Ms.” );

The ternary operator can be useful, but it’s also the hardest conditional in Java to understand. As you learn Java, you don’t encounter any situations where the ternary operator must be used instead of if-elsestatements.

Watching the Clock

The next project gives you another look at each of the conditional tests you can use in your programs. For this project, you use Java’s built-in time- keeping feature, which keeps track of the current date and time, and pres- ent this information in sentence form.

Run NetBeans (or another program to create Java programs) and give a new class the name Clock. This program is long, but most of it consists of long conditional statements. Type the full text of Listing 7.3 into the source code editor, and save the file.

ptg7068951 LISTING 7.3 TheClockProgram

1: import java.util.*;

2:

3: class Clock {

4: public static void main(String[] arguments) { 5: // get current time and date

6: Calendar now = Calendar.getInstance();

7: int hour = now.get(Calendar.HOUR_OF_DAY);

8: int minute = now.get(Calendar.MINUTE);

9: int month = now.get(Calendar.MONTH) + 1;

10: int day = now.get(Calendar.DAY_OF_MONTH);

11: int year = now.get(Calendar.YEAR);

12:

13: // display greeting 14: if (hour < 12) {

15: System.out.println(“Good morning.\n”);

16: } else if (hour < 17) {

17: System.out.println(“Good afternoon.\n”);

18: } else {

19: System.out.println(“Good evening.\n”);

20: } 21:

22: // begin time message by showing the minutes 23: System.out.print(“It’s”);

24: if (minute != 0) {

25: System.out.print(“ “ + minute + “ “);

26: System.out.print( (minute != 1) ? “minutes” : 27: “minute”);

28: System.out.print(“ past”);

29: } 30:

31: // display the hour 32: System.out.print(“ “);

33: System.out.print( (hour > 12) ? (hour - 12) : hour );

34: System.out.print(“ o’clock on “);

35:

36: // display the name of the month 37: switch (month) {

38: case 1:

39: System.out.print(“January”);

40: break;

41: case 2:

42: System.out.print(“February”);

43: break;

44: case 3:

45: System.out.print(“March”);

46: break;

47: case 4:

48: System.out.print(“April”);

49: break;

50: case 5:

51: System.out.print(“May”);

ptg7068951

Watching the Clock 89

52: break;

53: case 6:

54: System.out.print(“June”);

55: break;

56: case 7:

57: System.out.print(“July”);

58: break;

59: case 8:

60: System.out.print(“August”);

61: break;

62: case 9:

63: System.out.print(“September”);

64: break;

65: case 10:

66: System.out.print(“October”);

67: break;

68: case 11:

69: System.out.print(“November”);

70: break;

71: case 12:

72: System.out.print(“December”);

73: } 74:

75: // display the date and year

76: System.out.println(“ “ + day + “, “ + year + “.”);

77: } 78: }

After the program compiles correctly, look it over to get a good idea about how the conditional tests are being used.

With the exception of Line 1 and Lines 6–11, the Clockprogram contains material that has been covered up to this point. After a series of variables are set up to hold the current date and time, a series of ifor switchcondi- tionals are used to determine what information should be displayed.

This program contains several uses of System.out.println()and System.out.print()to display strings.

Lines 6–11 refer to a Calendarvariable called now. The Calendarvariable type is capitalized because Calendaris an object.

You learn how to create and work with objects during Hour 10, “Creating Your First Object.” For this hour, focus on what’s taking place in those lines rather than how it’s happening.

LISTING 7.3 Continued

ptg7068951 The Clockprogram is made up of the following sections:

. Line 1 enables your program to use a class that is needed to track the current date and time: java.util.Calendar.

. Lines 3–4 begin the Clockprogram and its main()statement block.

. Line 6 creates a Calendarobject called nowthat contains the current date and time of your system. The nowobject changes each time you run this program. (Unless the physical laws of the universe are altered and time stands still).

. Lines 7–11 create variables to hold the hour, minute, month, day, and year. The values for these variables are pulled from the Calendar object, which is the storehouse for all this information.

. Lines 14–20 display one of three possible greetings: “Good morn- ing.”, “Good afternoon.”, or “Good evening.” The greeting to display is selected based on the value of the hourvariable.

. Lines 23–29 display the current minute along with some accompany- ing text. First, the text “It’s” is displayed in Line 23. If the value of minuteis equal to 0, Lines 25–28 are ignored because of the ifstate- ment in Line 24. This statement is necessary because it would not make sense for the program to tell someone that it’s 0 minutes past an hour. Line 25 displays the current value of the minutevariable. A ternary operator is used in Lines 26–27 to display either the text

“minutes” or “minute,” depending on whether minuteis equal to 1.

Finally, in Line 28 the text pastis displayed.

. Lines 32–34 display the current hour by using another ternary opera- tor. This ternary conditional statement in Line 33 causes the hour to be displayed differently if it is larger than 12, which prevents the computer from stating times like “15 o’clock.”

. Lines 37–73, almost half of the program, are a long switchstatement that displays a different name of the month based on the integer value stored in the monthvariable.

. Line 76 finishes off the display by showing the current date and the year.

. Lines 77–78 close out the main()statement block and then the entire Clockprogram.

When you run this program, the output should display a sentence based on the current date and time. The output of the application is shown in the Output pane in Figure 7.3.

ptg7068951

Summary 91

Run the program several times to see how it keeps up with the clock.

Summary

Now that you can use conditional statements, the overall intelligence of your Java programs has improved greatly. Your programs can evaluate information and use it to react differently in different situations, even if information changes as the program is running. They can decide between two or more alternatives based on specific conditions.

Programming a computer forces you to break a task down into a logical set of steps to undertake and decisions that must be made. Using the ifstate- ment and other conditionals in programming also promotes a type of logi- cal thinking that can reap benefits in other aspects of your life:

. “Ifhe is elected president in November, I will seek a Cabinet posi- tion, elseI will move to Canada.”

. “Ifmy blind date is attractive, I’ll pay for dinner at an expensive restaurant, elsewe will go to Pizza Hut.”

. “IfI violate my probation, the only team that will draft me is the Philadelphia Eagles.”

FIGURE 7.3

The output of the Clockprogram.

ptg7068951

Q&A

Q. Theifstatement seems like the one that’s most useful. Is it possible to use only ifstatements in programs and never use the others?

A. It’s possible to do without elseorswitch, and many programmers never use the ternary operator ?. However,elseandswitchoften are beneficial to use in your programs because they make the programs easier to understand. A set of ifstatements chained together can become unwieldy.

Q. In the Clockprogram, why is 1 added to Calendar.MONTHto get the current month value?

A. This is necessary because of a quirk in the way that the Calendar class represents months. Instead of numbering them from 1 to 12 as you might expect, Calendar numbers months beginning with 0 in January and ending with 11 in December. Adding 1 causes months to be repre- sented numerically in a more understandable manner.

Q. During this hour, opening and closing brackets {and}are not used with an ifstatement if it is used in conjunction with only one state- ment. Isn’t it mandatory to use brackets?

A. No. Brackets can be used as part of any ifstatement to surround the part of the program that’s dependent on the conditional test. Using brackets is a good practice to get into because it prevents a common error that might take place when you revise the program. If you add a second statement after an ifconditional and don’t add brackets, unex- pected errors occur when the program is run.

Q. Doesbreakhave to be used in each section of statements that follow acase?

A. You don’t have to use break. If you do not use it at the end of a group of statements, all the remaining statements inside the switch block statement are handled, regardless of the case value they are being tested with. However, in most cases you’re likely to want a breakstate- ment at the end of each group.

Q. Why did the Thompson Twins get that name when they were a trio, they were not related, and none of them was named Thompson?

A. Band members Tom Bailey, Alannah Currie, and Joe Leeway called them- selves the Thompson Twins in honor of Thomson and Thompson, a pair of bumbling detectives featured in the Belgian comic books The Adventures of Tintin.

Một phần của tài liệu sams teach yourselfa java in 24 hours 6th edition (Trang 88 - 104)

Tải bản đầy đủ (PDF)

(429 trang)