Java Programming for absolute beginner- P6 pptx

20 325 0
Java Programming for absolute beginner- P6 pptx

Đ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

Nesting if-else Structures So far, you are able to conditionally execute one of two statements based on a sin- gle condition. Sometimes you need to have more than two branches in the flow of your program based on a set of related conditions. This is possible in Java. You know that in the if-else structure, the statement (any valid Java statement) that the program executes if the condition is false follows the else keyword. The key here is any valid Java statement—including another conditional statement. These types of structures are called nested if-else statements. Take a look at the syntax: if (condition1) { java_statements_for_true_condition1; } else if (condition2) { java_statements_for_true_condition2; } else { java_statements_for_false_conditions; } If condition1 is true, the program executes java_statements_for_true_condi- tion1 . If condition1 is false, condition2 is tested. You do this by immediately fol- lowing the else keyword with another if conditional statement. If condition2 is true, the program executes java_statements_for_true_condition2. Finally, if neither condition is true the java_statements_for_false_conditions are exe- cuted. Take a look at this quick example, and then move on to the next section where you use apply this concept in an actual program: if (name == “Joseph”) { System.out.println(name + “ is my first name.”); } else if (name == “Russell”) { System.out.println(name + “ is my last name.”); } else { System.out.println(name + “ is not my name.”); } 78 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 3.10 This is several runs of the HighOrLowTemp program. JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 78 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Assume that name is a string holding some person’s name. This snippet of code indicates that the name is my first name if it is “Joseph“, else if it is “Russell“, the code indicates that it is my last name. If it is neither my first name nor my last name, the code indicates that it is not my name. The ManyTemps Program The ManyTemps program demonstrates the use of the nested if-else structure. It prints a different message depending on the range of the randomly generated temperature. /* * ManyTemps * Demonstrates if-else nesting structure. */ import java.util.Random; public class ManyTemps { public static void main(String args[]) { int min = -40; int max = 120; int diff = max - min; int temp; Random rand = new Random(); temp = rand.nextInt(diff + 1) + min; System.out.println(“The temperature is “ + temp +”F.”); if (temp < -20) { System.out.println(“It’s DANGEROUSLY FREEZING! Stay home.”); } else if (temp < 0) { System.out.println(“It’s extremely cold! Bundle up tight.”); } else if (temp < 33) { System.out.println(“It’s cold enough to snow.”); } else if (temp < 50) { System.out.println(“You should bring a coat.”); } else if (temp < 70) { System.out.println(“It’s nice and brisk.”); } else if (temp < 90) { System.out.println(“It’s warm outside.”); } else if (temp < 100) { System.out.println(“It’s hot. Stay in the shade.”); } 79 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 79 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. else { System.out.println(“I hope you have an air conditioner!”); } } } There are a couple of things to explain here. One thing is that you can nest as many if-else statements as you need to. Another thing worth mentioning is with the way that these if conditions are nested here, you can assume the value of the conditions that are evaluated in previous if conditions within the same nested structure. The first condition temp < –20 assumes nothing about temp except that it can be less than –20. The next condition temp < 0 assumes that the temperature is not less than –20 because if it were, the program would never get to this point. So if the condition temp < 0 evaluates to true, the program right- fully assumes the temperature ranges somewhere between –20 and –1. This is why, although temp is random, the final else statement can assume that the tem- perature is not less than 100 and can safely mention the air conditioner. Figure 3.11 displays the output of several runs of this program. 80 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r Indentation and Syntax Conventions As you can see in all the examples using the if statement, for the sake of read- ability, I tend to use the following spacing and syntax conventions for if-else structures. Other people might have their own style. I follow the if keyword with a space, and then I type the condition within the parentheses. Within the con- dition, I use spaces between operands and operators. I also tend to use parenthe- ses, even when technically not necessary, within the conditional expression if the evaluation order could possibly be confusing later. After the condition, I use a space and then open the brace for the block statement that executes if the condition is true. As you read later chapters, you notice that FIGURE 3.11 The ManyTemps program conditionally prints one of eight messages. JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 80 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. I don’t always use braces. If there is only one simple statement that follows the condition, I tend to omit the brace; however, in nested if-else statements, or any other if statements that might be confusing, I use them. I indent lines within the braces two or three spaces, so they will be quickly identifiable as being part of the block statement. I always close braces on lines of their own and use the same indentation I used with the line with the opening brace. You can develop your own style of spacing and indentation, but keep in mind that in the real world, your company might have its own conventions that it requires all of its programmers to follow. In any case, keeping all of its code con- sistently formatted makes it so much more readable when working with other programmers’ code. Using the switch Statement Programmers commonly find themselves in situations where they need to test the value of an expression against some set of values. If the expression is not equal to the first value, test it against the second value. If the expression is not equal to the second value, test it against the third one, and so on. You can accom- plish this with an if-else structure, but there is an alternative, neater, way to do it. Consider printing a text description of a number, n, that can range from one through five. Using the if-else structure, you do it this way: if (n == 1) { System.out.println(“one”); } else if (n == 2) { System.out.println(“two”); } else if (n == 3) { System.out.println(“three”); } else if (n == 4) { System.out.println(“four”); } else if (n == 5) { System.out.println(“five”); } else { System.out.println(“some other number”); } You can see how many times I needed to repeat the n variable. You can probably also imagine how confusing this structure would be if I were testing for even more different values or if n wasn’t just a variable, but a complex expression that would need to be repeated in each condition. Take a look at how I write this using the switch statement: 81 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s JavaProgAbsBeg-03.qxd 2/25/03 8:49 AM Page 81 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. switch (n) { case 1: System.out.println(“one”); break; case 2: System.out.println(“two”); break; case 3: System.out.println(“three”); break; case 4: System.out.println(“four”); break; case 5: System.out.println(“five”); break; default: System.out.prinln(“some other number”); } You can immediately see that I only have to reference the n variable once in this switch block. The syntax for the switch conditional statement is as follows: switch (expression) { case value1: statements_for_value1; break; case value2: statements_for_value2; break; case value3: statements_for_value3; break; default: statements_for_any_other_value; } The switch keyword is followed by an expression in parentheses. The type of this expression must evaluate to char, byte, short, or int. If it doesn’t, you get a compile-time error. After the expression, you open the block using the brace. Fol- lowing that is the case keyword, and then the value to compare the expression to and a colon. After the colon, place any statements to be executed if the expres- sion is equal to the value that follows this particular case. After that, you use the break keyword to exit the switch statement. The default keyword, which is optional, is used to define statements that execute if the expression doesn’t equal any of the case values. The switch block is useful if you need to perform one action for multiple values. Take the following switch block that prints a message for multiples of 10 as an example: TRICK 82 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-03.qxd 2/25/03 8:50 AM Page 82 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. switch (n) { case 1: case 2: case 5: case 10: System.out.println(n + “ is a multiple of 10.”); break; default: System.out.println(n + “ is not a multiple of 10.”); } The cases in which n is a multiple of 10 do not have any statements in them (although they can), most importantly though, they don’t use the break statement. This allows the appropriate message to print for values 1, 2, 5, or 10. 83 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s WAR STORY When switch statements were fairly new to me I kept forgetting to use the break statements and I was getting some weird results. If you don’t use the break statements where you need to, the flow of the switch block moves into the next case statement and executes whatever other statements it finds there. I was baffled by what was going on. I was working with random numbers, but my results weren’t random. Of course, I automatically assumed that there was some problem with the way my code was generating random numbers. I wasted a lot of time before I finally realized what my mistake was. If you get into the habit of always using if structures and hardly ever using switch, like I once did, try not to forget about the break statements when you actually do use a switch block. The FuzzyDice Program This program uses the switch conditional structure to print the face value of one die. The face value of the die is generated randomly and the program tests it for values being equal to one of the face values of a six-sided die: 1 through 6. Here is the source code listing for FuzzyDice.java: /* * FuzzyDice * Demonstrates use of the switch structure */ import java.util.Random; public class FuzzyDice { JavaProgAbsBeg-03.qxd 2/25/03 8:50 AM Page 83 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. public static void main(String args[]) { Random random = new Random(); int die; String s; System.out.println(“Rolling die ”); die = random.nextInt(6) + 1; s = “\n ”; switch (die) { case 1: s = s + “\n| |”; s = s + “\n| * |”; s = s + “\n| |”; break; case 2: s = s + “\n| * |”; s = s + “\n| |”; s = s + “\n| * |”; break; case 3: s = s + “\n| * |”; s = s + “\n| * |”; s = s + “\n| * |”; break; case 4: s = s + “\n| * * |”; s = s + “\n| |”; s = s + “\n| * * |”; break; case 5: s = s + “\n| * * |”; s = s + “\n| * |”; s = s + “\n| * * |”; break; case 6: s = s + “\n| * * |”; s = s + “\n| * * |”; s = s + “\n| * * |”; break; default: //should never get here s = s + “\n| |”; s = s + “\n| |”; s = s + “\n| |”; } s = s + “\n ”; System.out.println(s); } } 84 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-03.qxd 2/25/03 8:50 AM Page 84 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. die is a random integer ranging inclusively from 1 through 6. The switch block uses the die variable as its expression. The program tests the value and condi- tionally builds a string that represents a “drawing” of the face of the die based on its value. If the program generates the random number correctly, it will never reach the default statements that build a string that represents a blank die face. Figure 3.12 demonstrates a couple of runs of this program. 85 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s Understanding Arrays An array is a list of primitive data type values or objects. It is a way to store col- lections of items of the same data type under one variable name. Arrays are actu- ally objects themselves and can be treated as such. You’ve already worked with arrays somewhat in Chapter 2 when you learned about accepting command-line arguments. Recall that the single parameter accepted by an application’s main() method is an array of strings. Now you learn about arrays in more detail. To cre- ate an array, you need to declare it, assign it an array object, and then you can assign actual values within the array. Declaring an Array When declaring an array, you need to specify the data type that the array will maintain in its list. You need to give it a variable name and specify it as being an array by using square brackets ( []). Here are a few examples of declaring arrays: int sillyNumbers[]; double mealPrices[]; Object objectList[]; boolean testAnswers[]; You can use the brackets where they are used previously, or you can optionally use the brackets after the data type. When I declare arrays, I do it this way: FIGURE 3.12 The FuzzyDice program randomly creates pictures of the face of a die. JavaProgAbsBeg-03.qxd 2/25/03 8:50 AM Page 85 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. int[] sillyNumbers; double[] mealPrices; Object[] objectList; boolean[] testAnswers; After you declare an array variable, you need to assign an array object to it before you can start using it. You do this by using the new keyword like you do when cre- ating any new object. You have to specify the array length, which is its size, or more specifically, the number of items it can hold—its capacity. You define the length of an array within the square brackets of the array object you are creating. The following examples assign array objects to the arrays declared previously: sillyNumbers = new int[10]; mealPrices = new double[18]; objectList = new Object[3]; testAnswers = new boolean[100]; After these array objects are created, sillyNumbers is an array able to hold 10 integers, mealPrices is an array able to hold 18 doubles, objectList is an array able to hold 3 objects, and testAnswers is an array able to hold 100 Booleans. Assigning Values to and Accessing Array Elements After you declare an array and assign an array object to it, you can assign values to the array elements. Array elements are the individual values stored under spe- cific subscripts of the array. Array subscripts are integers that represent an item’s position within the array. An array subscript is also called an array index. The element’s subscript is specified within square brackets that follow the array’s name. Here are some examples to clear things up: sillyNumbers[0] = 3000; sillyNumbers[9] = 1; The first line assigns 3000 to the first element of the sillyNumbers array. The first element of an array is always indexed by 0. The second line assigns the integer 1 to the array’s last element. Note that the subscript of the last element of an array is equal to one less than the array’s total length because the subscripts start at 0, not 1. You can also declare an array, assign an array object, and assign values to the array’s elements on one line. The following line declares an array of strings, family. Using braces and specifying the elements’ values, in order, separated by commas initializes the elements of the array. The length of family is 5 because it is initialized using 5 strings: String[] family = {“Vito”, “Santino”, “Michael”, “Fredo”, “Connie”}; 86 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-03.qxd 2/25/03 8:50 AM Page 86 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. After initializing this array, family[0] is “Vito”, family[1] is “Santino”, and so on. Let’s get rid of “Fredo” because he sleeps with the fishes: family[3] = null; Okay, that’s taken care of. You can access elements that are already stored in the array by using its subscript, just like when you assign its value. When you access an array element, you can treat it like any other variable of the same type. For example: System.out.println(“Don “ + family[0] + “ Corleone”); This line prints “Don Vito Corleone”. You can get the length of an array by using the syntax: arrayName.length. Remember that the last subscript of an array is one less than its length. If you attempt to access an element of an array by using a subscript that is out of the array’s bounds (by using a number that is not a subscript of the array, usually greater than the last subscript), you get a run-time error, as shown in Figure 3.13. The ArrayOOB program demonstrates this. The source code listing for Array- OOB.java is listed here: /* * ArrayOOB * Demonstrates what happens when an array index * is out of bounds. */ public class ArrayOOB { public static void main(String args[]) { //declare an array of length 10 int[] arr = new int[10]; //incorrect attempt to access its last value System.out.println(“Last value: “ + arr[10]); 87 C h a p t e r 3 T h e F o r t u n e T e l l e r : R a n d o m N u m b e r s, C o n d i t i o n a l s, a n d A r r a y s FIGURE 3.13 This program causes an ArrayIndexOutOf BoundsException and crashes. JavaProgAbsBeg-03.qxd 2/25/03 8:50 AM Page 87 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... Racer .java is as follows: Chapter 4 it in a loop that accounts for all of the employees You learn all about loops in this section More specifically, in this section, you learn about the for loop and the ++ (increment) operator JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 96 96 Java Programming for the Absolute Beginner The for Loop The for loop is typically used to reiterate a block of code a set number... 1]); JavaProgAbsBeg-03.qxd 2/25/03 8:50 AM Page 90 90 Java Programming for the Absolute Beginner Back to the Fortune Teller The FortuneTeller program that was introduced at the beginning of this chapter is listed here At this point, you should be able to understand all the code within this program It creates a Random object randini to generate random numbers Then it builds an array of Strings called fortunes...JavaProgAbsBeg-03.qxd 2/25/03 8:50 AM Page 88 Java Programming for the Absolute Beginner 88 //program will crash before it gets here System.out.println(“Is anyone alive out there?”); } } Multidimensional Arrays In Java, multidimensional arrays are actually arrays of arrays, or a list of lists Multidimensional arrays use sets of square brackets—one for each dimension of the... Here is the full listing of FortuneTeller .java: /* * FortuneTeller * A game that predicts the future * Demonstrates the usefulness of random numbers, arrays, * and conditionals in creating dynamic programs */ import java. util.Random; public class FortuneTeller { public static void main(String args[]) { Random randini = new Random(); int fortuneIndex; String day; String[] fortunes = { “The world is going... loop • Use the while loop • Include the do loop • Include exception handling in your code TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-04.qxd 2/25/03 8:50 AM Page 94 Java Programming for the Absolute Beginner 94 The Project: The NumberGuesser In this application, users are prompted to guess a number... the Math class and how to use the methods it contains to perform mathematical functions You learned about the if state- TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark The Fortune Teller: Random Numbers, Conditionals, and Arrays fortuneIndex = randini.nextInt(fortunes.length); Chapter 3 “Your friends will treat you to... treat you to lunch.”, “You will meet someone famous.”, “You will be very bored.”, “You will hear your new favorite song.”, “Tomorrow is too difficult to predict” }; JavaProgAbsBeg-03.qxd 2/25/03 8:50 AM Page 92 Java Programming for the Absolute Beginner 92 ment and conditional expressions and how to nest if-else statements to create multiple branches that conditionally affect the flow of your programs... postfix The postfix increment is evaluated after any assignments or operations are performed, whereas the prefix increment is evaluated before any assignments or operations are performed For example, the following code fragment results in the value 2 being assigned to y: int y, x = 1; y = ++x; because x is incremented before y gets its value The following code fragment, on the other hand, results in the... to perform the same action on multiple data For example, you might write a payroll program that loops on all of a company’s employees and cuts them a check Instead of writing code to handle all of the employees separately, you write code that cuts a check and then put TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-04.qxd... is not that straightforward either This program is not much more than a loop It prints Go! before the loop starts, iterates through the loop 10 times, and then prints Finish! after the loop terminates While inside the loop, it prints the number of laps (iterations) through the loop Write this application and run it Take notice of how quickly the program runs The source for Racer .java is as follows: . { java_ statements _for_ true_condition1; } else if (condition2) { java_ statements _for_ true_condition2; } else { java_ statements _for_ false_conditions; } If condition1 is true, the program executes java_ statements _for_ true_condi- tion1 statement. If condition2 is true, the program executes java_ statements _for_ true_condition2. Finally, if neither condition is true the java_ statements _for_ false_conditions are exe- cuted. Take a look. syntax for the switch conditional statement is as follows: switch (expression) { case value1: statements _for_ value1; break; case value2: statements _for_ value2; break; case value3: statements _for_ value3; break; default: statements _for_ any_other_value; } The

Ngày đăng: 03/07/2014, 05:20

Từ khóa liên quan

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

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

Tài liệu liên quan