Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.

Similar presentations


Presentation on theme: "© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement."— Presentation transcript:

1 © 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both See Wages.java (page 211)Wages.java

2 © 2004 Pearson Addison-Wesley. All rights reserved5-2 The Coin Class Let's examine a class that represents a coin that can be flipped Instance data is used to indicate which face (heads or tails) is currently showing See CoinFlip.java (page 213)CoinFlip.java See Coin.java (page 214)Coin.java

3 © 2004 Pearson Addison-Wesley. All rights reserved5-3 Block Statements In an if-else statement, the if portion, or the else portion, or both, could be block statements if (total > MAX) { System.out.println ("Error!!"); errorCount++; } else { System.out.println ("Total: " + total); current = total*2; } See Guessing.java (page 216)Guessing.java

4 © 2004 Pearson Addison-Wesley. All rights reserved5-4 The Conditional Operator Java has a conditional operator that uses a boolean condition to determine which of two expressions is evaluated Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression

5 © 2004 Pearson Addison-Wesley. All rights reserved5-5 The Conditional Operator The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger ; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands

6 © 2004 Pearson Addison-Wesley. All rights reserved5-6 The Conditional Operator Another example: System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); If count equals 1, then "Dime" is printed If count is anything other than 1, then "Dimes" is printed

7 © 2004 Pearson Addison-Wesley. All rights reserved5-7 The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches

8 © 2004 Pearson Addison-Wesley. All rights reserved5-8 The switch Statement The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... } switch and case are reserved words If expression matches value2, control jumps to here

9 © 2004 Pearson Addison-Wesley. All rights reserved5-9 The switch Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

10 © 2004 Pearson Addison-Wesley. All rights reserved5-10 The switch Statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } An example of a switch statement:

11 © 2004 Pearson Addison-Wesley. All rights reserved5-11 The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch

12 © 2004 Pearson Addison-Wesley. All rights reserved5-12 The switch Statement The expression of a switch statement must result in an integral type, meaning an integer ( byte, short, int, long ) or a char It cannot be a boolean value or a floating point value ( float or double ) The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement See GradeReport.java (page 225)GradeReport.java

13 © 2004 Pearson Addison-Wesley. All rights reserved5-13 Comparing Strings Remember that in Java a character string is an object The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name");

14 © 2004 Pearson Addison-Wesley. All rights reserved5-14 The while Statement Let's look at some examples of loop processing A loop can be used to maintain a running sum A sentinel value is a special input value that represents the end of input See Average.java (page 229)Average.java A loop can also be used for input validation, making a program more robust See WinPercentage.java (page 231)WinPercentage.java

15 © 2004 Pearson Addison-Wesley. All rights reserved5-15 Infinite Loops An example of an infinite loop: int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } This loop will continue executing until interrupted (Control- C) or until an underflow error occurs

16 © 2004 Pearson Addison-Wesley. All rights reserved5-16 Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely See PalindromeTester.java (page 235)PalindromeTester.java

17 © 2004 Pearson Addison-Wesley. All rights reserved5-17 Nested Loops How many times will the string "Here" be printed? count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) { System.out.println ("Here"); count2++; } count1++; } 10 * 20 = 200

18 © 2004 Pearson Addison-Wesley. All rights reserved7-18 Arrays An array is an ordered list of primitive types of object references  An array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 scores The entire array has a single name Each value has a numeric index scores[2] refers to 94 scores[2] = 25;

19 © 2004 Pearson Addison-Wesley. All rights reserved7-19 Arrays The array itself is an object - must be instantiated int[] scores = new int[10]; The reference variable scores is set to a new array object that can hold 10 integers float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; float[] prices; // better float prices[];

20 © 2004 Pearson Addison-Wesley. All rights reserved7-20 Bounds Checking Once an array is created, it has a fixed size The index value must be in range 0 to N-1  The array codes can hold 100 values, indexed using only 0 to 99 for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; problem Public constant length: the size of the array codes.length 100 (not 99)

21 © 2004 Pearson Addison-Wesley. All rights reserved7-21 Bounds Checking See ReverseOrder.java (page 375) ReverseOrder.java See LetterCount.java (page 376) LetterCount.java

22 © 2004 Pearson Addison-Wesley. All rights reserved7-22 Initializer lists char[] letterGrades = {'A', 'B', 'C', 'D', ’F’}  the new operator is not used  no size value is specified – it is the number of items in the initializer list  an initializer list can be used only in the array declaration  See Primes.java (page 381)Primes.java

23 © 2004 Pearson Addison-Wesley. All rights reserved7-23 Arrays as Parameters An entire array can be passed as a parameter to a method Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other Therefore, changing an array element within the method changes the original An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type

24 © 2004 Pearson Addison-Wesley. All rights reserved7-24 Arrays of Objects The elements of an array can be object references The following declaration reserves space to store 5 references to String objects String[] words = new String[5]; It does NOT create the String objects themselves Initially an array of objects holds null references Each object stored in an array must be instantiated separately

25 © 2004 Pearson Addison-Wesley. All rights reserved7-25 Arrays of Objects The words array when initially declared: words - - - - - At this point, the following reference would throw a NullPointerException : System.out.println (words[0]);

26 © 2004 Pearson Addison-Wesley. All rights reserved7-26 Arrays of Objects After some String objects are created and stored in the array: “friendship” words - - “loyalty” “honor”

27 © 2004 Pearson Addison-Wesley. All rights reserved7-27 Arrays of Objects Keep in mind that String objects can be created using literals The following declaration creates an array object called verbs and fills it with four String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep"};

28 © 2004 Pearson Addison-Wesley. All rights reserved7-28 Arrays of Objects The following example creates an array of Grade objects, each with a string representation and a numeric lower bound See GradeRange.java (page 384) GradeRange.java See Grade.java (page 385) Grade.java Now let's look at an example that manages a collection of CD objects See Tunes.java (page 387) Tunes.java See CDCollection.java (page 388) CDCollection.java See CD.java (page 391) CD.java

29 © 2004 Pearson Addison-Wesley. All rights reserved7-29 Command-Line Arguments The signature of the main method indicates that it takes an array of String objects as a parameter These values come from command-line arguments that are provided when the interpreter is invoked For example, the following invocation of the interpreter passes three String objects into main : > java StateEval pennsylvania texas arizona These strings are stored at indexes 0-2 of the array parameter of the main method See NameTag.java (page 393) NameTag.java

30 © 2004 Pearson Addison-Wesley. All rights reserved7-30 Variable Length Parameter Lists Suppose we wanted to create a method that processed a different amount of data from one invocation to the next For example, let's define a method called average that returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75);

31 © 2004 Pearson Addison-Wesley. All rights reserved7-31 Variable Length Parameter Lists We could define overloaded versions of the average method  Downside: we'd need a separate version of the method for each parameter count We could define the method to accept an array of integers  Downside: we'd have to create the array and store the integers prior to calling the method each time Instead, Java provides a convenient way to create variable length parameter lists

32 © 2004 Pearson Addison-Wesley. All rights reserved7-32 Variable Length Parameter Lists Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the same type For each call, the parameters are automatically put into an array for easy processing in the method public double average (int... list) { // whatever } element type array name Indicates a variable length parameter list

33 © 2004 Pearson Addison-Wesley. All rights reserved7-33 Variable Length Parameter Lists public double average (int... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result; }

34 © 2004 Pearson Addison-Wesley. All rights reserved7-34 Variable Length Parameter Lists The type of the parameter can be any primitive or object type public void printGrades (Grade... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); }

35 © 2004 Pearson Addison-Wesley. All rights reserved7-35 Variable Length Parameter Lists A method that accepts a variable number of parameters can also accept other parameters The following method accepts an int, a String object, and a variable number of double values into an array called nums public void test (int count, String name, double... nums) { // whatever }

36 © 2004 Pearson Addison-Wesley. All rights reserved7-36 Variable Length Parameter Lists The varying number of parameters must come last in the formal arguments A single method cannot accept two sets of varying parameters Constructors can also be set up to accept a variable number of parameters See VariableParameters.java (page 396) VariableParameters.java See Family.java (page 397) Family.java

37 © 2004 Pearson Addison-Wesley. All rights reserved7-37 Two-Dimensional Arrays A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions

38 © 2004 Pearson Addison-Wesley. All rights reserved7-38 Two-Dimensional Arrays An array of arrays Specify the size of each dimension separately: int[][] scores = new int[12][50]; value = scores[3][6] The array stored in one row can be specified using one index

39 © 2004 Pearson Addison-Wesley. All rights reserved7-39 Two-Dimensional Arrays ExpressionTypeDescription tableint[][] 2D array of integers, or array of integer arrays table[5]int[] array of integers table[5][12]int integer See TwoDArray.java (page 399) TwoDArray.java See SodaSurvey.java (page 400) SodaSurvey.java

40 © 2004 Pearson Addison-Wesley. All rights reserved7-40 Multidimensional Arrays An array can have many dimensions – if it has more than one dimension, it is called a multidimensional array Each dimension subdivides the previous one into the specified number of elements Each dimension has its own length constant Because each dimension is an array of array references, the arrays within one dimension can be of different lengths  these are sometimes called ragged arrays

41 © 2004 Pearson Addison-Wesley. All rights reserved7-41 The ArrayList Class The ArrayList class is part of the java.util package Like an array, it can store a list of values and reference each one using a numeric index However, you cannot use the bracket syntax with an ArrayList object Furthermore, an ArrayList object grows and shrinks as needed, adjusting its capacity as necessary

42 © 2004 Pearson Addison-Wesley. All rights reserved7-42 The ArrayList Class Elements can be inserted or removed with a single method invocation When an element is inserted, the other elements "move aside" to make room Likewise, when an element is removed, the list "collapses" to close the gap The indexes of the elements adjust accordingly

43 © 2004 Pearson Addison-Wesley. All rights reserved7-43 The ArrayList Class An ArrayList stores references to the Object class, which allows it to store any kind of object See Beatles.java (page 405) Beatles.java We can also define an ArrayList object to accept a particular type of object The following declaration creates an ArrayList object that only stores Family objects ArrayList reunion = new ArrayList This is an example of generics, which are discussed further in Chapter 12

44 © 2004 Pearson Addison-Wesley. All rights reserved7-44 ArrayList Efficiency The ArrayList class is implemented using an underlying array The array is manipulated so that indexes remain continuous as elements are added or removed If elements are added to and removed from the end of the list, this processing is fairly efficient But as elements are inserted and removed from the front or middle of the list, the remaining elements are shifted


Download ppt "© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement."

Similar presentations


Ads by Google