Java By Example PHẦN 3 pdf

59 312 0
Java By Example PHẦN 3 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

But, wait a second-you're not done yet. You can still find more sub-expressions. Look at the multiplication operation. Can you see that it's multiplying two expressions together? Those two expressions look like this: (5 - x) (2 + y) And the above simplified expressions contain yet more sub-expressions. Those expressions are: 5 x 2 y Expressions are what programmers like to call recursive, meaning that the definition of an expression keeps coming back on itself. An expression contains expressions that contain other expressions, which themselves contain other expressions. How deep you can dig depends on the complexity of the original expression. But, as you saw demonstrated, even the relatively simple expression num = (5 - x) * (2 + y) has four levels of depth. Comparison Operators Now that you've dug into the secrets of expressions, it's time to learn about a new type of operator. So far, you've gotten some practice with mathematical operators, which enable you to build various types of numerical and assignment expressions. Another type of operator you can use to build expressions is the comparison operator. Comparison operators are used to create logical expressions, which, if you recall, result in a value of true or false. Table 8.1 lists the logical expressions used in Java programming. C and C++ programmers will find these operators very familiar. Table 8.1 Java's Logical Operators. Operators Description == Equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to != Not equal to Example: Using Comparison Operators Just how do you use comparison operators? As their name suggests, you use them to compare two expressions, with the result of the comparison being either true or false. For example, look at this logical expression: 3 == 2 + 1 The result of the above expression is true because the == operator determines whether the expressions on either side are equal to each other. If you were to change the expression to 3 == 2 + 2 the result would be false. That is, 3 does not equal 4. However, the previous sentence suggests a way to rewrite the expression, like this: 3 != 2 + 2 This expression results in a value of true, because 3 does not equal 4. The other logical expressions work similarly. Table 8.2 lists a number of logical expressions and the results they produce. Table 8.2 Examples of Logical Expressions. Expression Result 3 + 4 == 7 true 3 + 4 != 7 false 3 + 4 != 2 + 6 true 3 + 4 < 10 true 3 + 4 <= 10 true 3 + 4 == 4 + 4 false 3 + 4 > 10 false 3 + 4 >= 7 true 3 + 4 >= 8 false Logical Operators The comparison operators enable you to compare two expressions. But another type of operator-logical operators-supercharges comparison operators so that you can combine two or more logical expressions into a more complex logical expression. Even if you've never programmed a computer before, you're already familiar with logical operators because you use them in everyday speech. For example, when you say, "Do you have a credit card or ten dollars in cash?" you're using the logical operator OR. Similarly, when you say, "I have a dog and a cat," you're using the AND operator. Table 8.3 lists Java's logical operators and what they mean. Table 8.3 Java's Logical Operators. Operator Description && AND || OR ^ Exclusive OR ! NOT The AND (&&) operator requires all expressions to be true for the entire expression to be true. For example, the expression (3 + 2 == 5) && (6 + 2 == 8) is true because the expressions on both sides of the && are true. However, the expression (4 + 3 == 9) && (3 + 3 == 6) is false because the expression on the left of the && is not true. Remember this when combining expressions with AND: If any expression is false, the entire expression is false. The OR operator (||) requires only one expression to be true for the entire expression to be true. For example, the expressions (3 + 6 == 2) || (4 + 4 == 8) and (4 + 1 == 5) || (7 + 2 == 9) are both true because at least one of the expressions being compared is true. Notice that in the second case both expressions being compared are true, which also makes an OR expression true. The exclusive OR operator (^) is used to determine if one and only one of the expressions being compared is true. Unlike a regular OR, with an exclusive OR, if both expressions are true, the result is false (weird, huh?). For example, the expression (5 + 7 == 12) ^ (4 + 3 == 8) evaluates to true, whereas these expressions evaluate to false: (5 + 7 == 12) ^ (4 + 3 == 7) (5 + 7 == 10) ^ (4 + 3 == 6) The NOT (!) operator switches the value of (or negates) a logical expression. For example, the expression (4 + 3 == 5) is false; however, the expression !(4 + 3 == 5) is true. Example: Using Logical Operators Take a look at the following expression: (4 + 5 == 9) && !(3 + 1 = 3) Is this expression true or false? If you said true, you understand the way the logical operators work. The expressions on either side of the && are both true, so the entire expression is true. If you said false, you must go to bed without any dinner. Example: Using Multiple Logical Operators Just as with mathematical operators, you can use multiple logical operators to compare several logical expressions. For example, look at this expression: (4 == 4) && (5 == 5) && (6 == 6) This expression gives a result of true because each expression to the left and right of each AND operator is true. However, this expression yields a value of false: (4 == 4) && (5 == 6) && (6 == 6) Remember that, when using AND, if any sub-expression is false, the entire expression is false. This is kind of like testifying in court. To be true, it's got to be the truth, the whole truth, and nothing but the truth. Example: Combining Different Comparison and Logical Operators Again, just like mathematical operators, there's no restriction on how you can combine the different comparison and logical operators, although if you build a very complex expression, you may have trouble evaluating it yourself. Check out this expression: (3 < 5) && (2 == 2) && (9 > 6) Here you've used four different comparison and logical operators in the same complex expression. But because you're comparing the sub-expressions with the AND operator, and because each of the sub- expressions is true, the result of the above expression is true. Now, look at this expression: ((3 < 5) && (2 == 1)) || (7 == 7) Yep, things are getting tricky. Is the above expression true or false? (Hey, give it a shot. You've got a fifty-fifty chance.) Ready for the answer? The above expression is true. First, look at the parentheses. The outermost parentheses, on the left, group the two expressions being compared by the AND operator into a single expression, so evaluate it first. The value 3 is less than 5, but 2 does not equal 1, so the entire expression on the left of the OR operator is false. On the right of the OR operator, however, 7 does indeed equal 7, so this sub-expression is true. Because one of the expressions in the OR comparison is true, the entire expression is true. Here's how the expression breaks down, step-by-step: ((3 < 5) && (2 == 1)) || (7 == 7) ((true) && (false)) || (7 == 7) false || (7 == 7) false || true true Writing Logical Expressions You wouldn't write expressions such as (4 + 5 == 9) && !(3 + 1 == 3) in your programs. They would serve no purpose because you already know how the expressions evaluate. However, when you use variables, you have no way of knowing in advance how an expression may evaluate. For example, is the expression (num < 9) && (num > 15) true or false? You don't know without being told the value of the numerical variable num. By using logical operators, though, your program can do the evaluation, and, based on the result-true or false- take the appropriate action. In the next chapter, which is about if and switch statements, you'll see how your programs can use logical expressions to make decisions. Order of Operations Like all operators, comparison and logical operators have an order of operations, or operator precedence. When you evaluate a complex expression, you must be sure to evaluate any sub-expressions in the correct order. As you learned in the previous example, however, you can use parentheses to group expressions so that they're easier to understand or to change the order of operations. Table 8.4 lists the comparison and logical operators in order of precedence. Table 8.4 Comparison and Logical Operators' Order of Operations. Operators Description ! NOT < > <= >= Relational == != Equality ^ Exclusive OR && Logical AND || Logical OR Summary Expressions, which are lines of Java code that can be reduced to a value or that assign a value, come in several types. In this chapter, you not only experimented with numerical and assignment expressions, but you also learned about logical expressions, which you create using the comparison and logical operators. Now that you know how to use comparison and logical operators to build logical expressions, you're ready to discover how computers make decisions. You'll make that discovery in the next chapter, where you'll also start using the operators you learned in order to write actual applets. Before you turn to that chapter, however, test your knowledge of expressions, comparison operators, and logical operators by answering the following review questions and by completing the review exercises. Review Questions 1. What is an expression? 2. What are the three types of expressions? 3. What is the result of the logical expression (3 < 5)? 4. What is the result of the logical expression (3 < 5) && (5 == 4 + 1)? 5. Explain why expressions are recursive in nature. 6. What are the six comparison operators? 7. What are the four logical operators? 8. What is the result of the logical expression (3 < 5) || (6 == 5) || (3 != 3)? 9. What's the result of the logical expression (5 != 10) && ((3 == 2 + 1) ||(4 < 2 + 5))? 10. What's the result of the logical expression !(5 == 2 + 3) && !(5 + 2 !=7 - 5)? Review Exercises 1. Write an expression that compares three numbers for equality. 2. Write an expression that determines whether one number is less than or equal to another. 3. Write an expression that uses three different types of comparison operators and two different types of logical operators. The expression must be false. 4. Suppose you have three variables, called num1, num2, and num3, in a program. Write an expression that compares the variables for equality. 5. If the variable num1 is equal to 5 and the variable num2 is equal to 10, how would you evaluate the logical expression ((num1 != 5) || (num2 == 10)) && !(num1 == 5)? Show each step of the evaluation. Chapter 9 The if and switch Statements CONTENTS ● Controlling Program Flow ● Program Flow and Branching ● The if statement ❍ Example: The Form of an if Statement ❍ Multiple if Statements ❍ Multiple-Line if Statements ❍ The else Clause ❍ Example: Using the if Statement in a Program ● The switch Statement ❍ Example: Using the break Statement Correctly ❍ Example: Using the switch Statement in a Program ● Summary ● Review Questions ● Review Exercises In previous chapters, you've learned a lot about the way Java works. You now know how to type and compile programs, how to input and output simple data, how to perform mathematical operations, and how to perform comparisons using logical expressions. But these techniques are merely the building blocks of a program. To use these building blocks in a useful way, you have to understand how computers make decisions. In this chapter, you learn how your programs can analyze data in order to decide what parts of your program to execute. Until now, your applets have executed their statements in strict sequential order, starting with the first line of a method and working, line by line, to the end of the method. Now it's time to learn how you can control your program flow-the order in which the statements are executed-so that you can do different things based on the data your program receives. Controlling Program Flow Program flow is the order in which a program executes its statements. Most program flow is sequential, [...]... enclose the commands within curly braces Listing 9 .3 is a revised version of Listing 9.2 that uses this technique Listing 9 .3 LST9 _3. LST: Multiple-Line if Statements if (choice == 1) { num = 1; num2 = 10; } if (choice == 2) { num = 2; num2 = 20; } if (choice == 3) { num = 3; num2 = 30 ; } TIP Notice that some program lines in Listing 9 .3 are indented By indenting the lines that go with each if block,... are surrounded by parentheses You follow the parentheses with the statement that you want executed if the logical expression is true For example, look at this if statement: if (choice == 5) g.drawString("You chose number 5.", 30 , 30 ); In this case, if the variable choice is equal to 5, Java will execute the call to drawString() Otherwise, Java will just skip the call to drawString() Example: The Form... CLASSES folder, naming the file Applet8 .java (You can copy the source code from the CD-ROM, if you like, and thus save on typing.) 2 Compile the source code by typing javac Applet8 .java at the MS-DOS prompt, which gives you the Applet8.class file 3 Type the HTML document shown in Listing 10 .3, and save it to your CLASSES folder under the name APPLET8.htmL 4 Run the applet by typing, at the MS-DOS prompt,... forward in your Java programming career You now have enough Java programming savvy to write simple, yet useful, applets Of course, that's not to say that there isn't a lot left to learn But by now you should have a good idea of what a Java applet looks like and how it works The remainder of this book will fill out the details that make Java applets so powerful Review Questions 1 2 3 4 5 6 7 8 9 What... doesn't force Java to evaluate all three if statements unless it really has to No problem Listing 9.5 shows you how to use the else if clause: Listing 9.5 LST9_5.LST: Using if and else Efficiently if (choice == 1) { num = 1; num2 = 10; } else if (choice == 2) { num = 2; num2 = 20; } else if (choice == 3) { num = 3; num2 = 30 ; } When Java executes the program code in Listing 9.5, if choice is 1, Java will... In the above example, if x equals 1, Java jumps to the case 1 and sets y equal to 1 Then, the break statement tells Java that it should skip over the rest of the switch statement If x is 2, the same sort of program flow occurs, except Java jumps to the case 2, sets y equal to 2, and then breaks out of the switch If the switch control variable is not equal to any of the values specified by the various... Control Program Flow switch(x) { case 1: y = 1; case 2: y = 2; break; case 3: y = 3; break; default: y = 0; } In this example, funny things happen, depending on whether the control variable x equals 1 or 2 In the former case, Java first jumps to case 1 and sets y equal to 1 Then, because there is no break before the case 2 clause, Java continues executing statements, dropping through the case 2 and setting... easily be converted from one to the other Listing 9.12 is a new version of Applet6 (called Applet7) that incorporates the menu example by using a switch statement instead of an if statement Listing 9.12 APPLET7 .JAVA: Using a switch Statement in a Program import java. awt.*; import java. applet.*; public class Applet7 extends Applet { TextField textField1; public void init() { textField1 = new TextField(5);... program Listing 9.6 is a Java program that uses the menu example you studied earlier in this chapter, whereas Listing 9.7 is the HTML document that runs the applet Figure 9.1 shows the applet running in the Appletviewer application Figure 9.1 : The Applet6 applet enables you to choose colors Listing 9.6 Applet6 .java: Using an if Statement in a Program import java. awt.*; import java. applet.*; public class... while Loop r Example: Using a while Loop r Example: Using a while Loop in a Program The do-while Loop r Example: Using a do-while Loop r Example: Using a do-while Loop in a Program Summary Review Questions Review Exercises A computer handles repetitive operations especially well-it never gets bored, and it can perform a task as well the 10,000th time as it did the first Consider, for example, a disk . Expressions. Expression Result 3 + 4 == 7 true 3 + 4 != 7 false 3 + 4 != 2 + 6 true 3 + 4 < 10 true 3 + 4 <= 10 true 3 + 4 == 4 + 4 false 3 + 4 > 10 false 3 + 4 >= 7 true 3 + 4 >= 8 false Logical. example, the expression (3 + 2 == 5) && (6 + 2 == 8) is true because the expressions on both sides of the && are true. However, the expression (4 + 3 == 9) && (3 + 3. (choice == 2) { num = 2; num2 = 20; } if (choice == 3) { num = 3; num2 = 30 ; } TIP Notice that some program lines in Listing 9 .3 are indented. By indenting the lines that go with each if block,

Ngày đăng: 12/08/2014, 19:21

Từ khóa liên quan

Mục lục

  • Java By Example

    • Chapter 9 -- The if and switch Statements

    • Chapter 10 -- The while and do-while Loops

    • Chapter 11 -- The for Loop

    • Chapter 12 -- Functions

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan