ch03
74 Pages

ch03

Course Number: CS 320, Fall 2009

College/University: Indiana State

Word Count: 16388

Rating:

Document Preview

Chapter 3 Decision Structures 3.1 The if Statement Chapter Topics 3.1 The if Statement The if-else Statement The if-else-if Statement Nested if Statements Logical Operators Comparing String Objects More about Variable Declaration and Scope The Conditional Operator (Optional) The switch Statement Creating Objects with the DecimalFormat Class The printf Method (Optional) Case Study on Student CD: Calculating...

Unformatted Document Excerpt
Coursehero >> Indiana >> Indiana State >> CS 320

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Structures 3.1 Chapter 3 Decision The if Statement Chapter Topics 3.1 The if Statement The if-else Statement The if-else-if Statement Nested if Statements Logical Operators Comparing String Objects More about Variable Declaration and Scope The Conditional Operator (Optional) The switch Statement Creating Objects with the DecimalFormat Class The printf Method (Optional) Case Study on Student CD: Calculating Sales Commission I n all the programs you have written so far, the statements are executed one after the other, in the order they appear. You might think of sequentially executed statements as the steps you take as you walk down a road. To complete the journey, you must start at the beginning and take each step, one after the other, until you reach your destination. This is illustrated in Figure 3-1. 3.2 3.3 3.4 3.5 3.6 3.7 3.8 CONCEPT THE 3.9 3.10 if STATEMENT IS USED TO CREATE A DECISION STRUCTURE, WHICH ALLOWS A PROGRAM TO HAVE MORE THAN ONE PATH OF EXECUTION. THE 3.11 if STATEMENT CAUSES ONE OR MORE STATEMENTS TO EXECUTE ONLY WHEN A boolean EXPRESSION IS true. 3.12 Common Errors to Avoid Review Questions and Exercises 117 118 Chapter 3 Decision Structures Figure 3-1 Sequence structure The type of code in Figure 3-1 is called a sequence structure, because the statements are executed in sequence, without branching off in another direction. Programs often need more than one path of execution, however. Many algorithms require a program to execute some statements only under certain circumstances. This can be accomplished with a decision structure. In a decision structures simplest form, a specific action is taken only when a condition exists. If the condition does not exist, the action is not performed. The flowchart in Figure 3-2 shows the logic of a decision structure. The diamond symbol represents a yes/no question or a true/false condition. If the answer to the question is yes (or if the condition is true), the program flow follows one path which leads to an action being performed. If the answer to the question is no (or the condition is false), the program flow follows another path which skips the action. In the flowchart, the action Wear a coat is only performed when it is cold outside. If it is not cold outside, the action is skipped. The action is conditionally executed because it is only performed when a certain condition (cold outside) exists. Figure 3-3 shows a more elaborate flowchart, where three actions are taken only when it is cold outside. One way to code a decision structure in Java is with the if statement. Here is the general format of the if statement: if(BooleanExpression) statement; Figure 3-2 Simple decision structure logic The if statement is simple in the way it works: The BooleanExpression that appears inside the parentheses must be a boolean expression. A boolean expression is one that is either true or false. If the boolean expression is true, the very next statement Figure 3-3 Three-action decision structure logic The if Statement 119 is executed. Otherwise, it is skipped. The statement is conditionally executed because it only executes under the condition that the expression in the parentheses is true. Using Relational Operators to Form Conditions Typically, the boolean expression that is tested by an if statement is formed with a relational operator. A relational operator determines whether a specific relationship exists between two values. For example, the greater than operator (>) determines whether one value is greater than another. The equal to operator (==) determines whether two values are equal. Table 3-1 lists all of the Java relational operators. 3 Table 3-1 Relational operators Relational Operators (in Order of Precedence) > < >= <= == != Meaning Greater than Less than Greater than or equal to Less than or equal to Equal to Not equal to All of the relational operators are binary, which means they use two operands. Here is an example of an expression using the greater than operator: length>width This expression determines whether length is greater than width. If length is greater than width, the value of the expression is true. Otherwise, the value of the expression is false. Because the expression can be only true or false, it is a boolean expression. The following expression uses the less than operator to determine whether length is less than width: length<width Table 3-2 shows examples of several boolean expressions that compare the variables x and y. 120 Chapter 3 Table 3-2 Decision Structures boolean expressions using relational operators Expression x>y x<y x>=y x<=y x==y x!=y Meaning Is Is Is Is Is Is x x x x x x greater than y? less than y? greater than or equal to y? less than or equal to y? equal to y? not equal to y? Two of the operators, >= and <=, test for more than one relationship. The >= operator determines whether the operand on its left is greater than or equal to the operand on the right. Assuming that a is 4, b is 6, and c is 4, both of the expressions b>=a and a>=c are true and a>=5 is false. When using this operator, the > symbol must precede the = symbol, and there is no space between them. The <= operator determines whether the operand on its left is less than or equal to the operand on its right. Once again, assuming that a is 4, b is 6, and c is 4, both a<=c and b<=10 are true, but b<=a is false. When using this operator, the < symbol must precede the = symbol, and there is no space between them. The == operator determines whether the operand on its left is equal to the operand on its right. If both operands have the same value, the expression is true. Assuming that a is 4, the expression a==4 is true and the expression a==2 is false. Notice the equality operator is two = symbols together. Dont confuse this operator with the assignment operator, which is one = symbol. The != operator is the not equal operator. It determines whether the operand on its left is not equal to the operand on its right, which is the opposite of the == operator. As before, assuming a is 4, b is 6, and c is 4, both a!=b and b!=c are true because a is not equal to b and b is not equal to c. However, a!=c is false because a is equal to c. Putting It All Together Lets look at an example of the if statement: if(sales>50000) bonus=500.0; This statement uses the > operator to determine whether sales is greater than 50,000. If the expression sales>50000 is true, the variable bonus is assigned 500.0. If the expression is false, however, the assignment statement is skipped. The program in Code Listing 3-1 shows another example. The user enters three test scores and the program calculates their average. If the average is greater than 95, the program congratulates the user on obtaining a high score. The if Statement 121 Code Listing 3-1 (AverageScore.java) 1 import javax.swing.JOptionPane; // Needed for JOptionPane 2 3 /** 4 This program demonstrates the if statement. 5 */ 6 7 public class AverageScore 8 { 9 public static void main(String[] args) 10 { 11 double score1; // To hold score #1 12 double score2; // To hold score #2 13 double score3; // To hold score #3 14 double average; // To hold the average score 15 String input; // To hold the users input 16 17//Getthefirsttestscore. 18input=JOptionPane.showInputDialog(Enterscore#1:); 19score1=Double.parseDouble(input); 20 21//Getthesecondscore. 22input=JOptionPane.showInputDialog(Enterscore#2:); 23score2=Double.parseDouble(input); 24 25//Getthethirdtestscore. 26input=JOptionPane.showInputDialog(Enterscore#3:); 27score3=Double.parseDouble(input); 28 29//Calculatetheaveragescore. 30average=(score1+score2+score3)/3.0; 31 32//Displaytheaveragescore. 33JOptionPane.showMessageDialog(null, 34Theaverageis+average); 35 36//Ifthescorewasgreaterthan95,lettheuserknow 37//that'sagreatscore. 38if(average>95) 39JOptionPane.showMessageDialog(null, 40That'sagreatscore!); 41 42System.exit(0); 43} 44} 3 122 Chapter 3 Decision Structures Figures 3-4 and 3-5 show examples of interaction with this program. In Figure 3-4 the average of the test scores is not greater than 95. In Figure 3-5 the average is greater than 95. This input dialog box appears first. The user enters 82 and then clicks on the OK button. This input dialog box appears next. The user enters 76 and then clicks on the OK button. This input dialog box appears next. The user enters 91 and then clicks on the OK button. This message dialog box appears next. The average of the three test scores is displayed. Figure 3-4 Interaction with the AverageScore program The if Statement 123 This input dialog box appears first. The user enters 92 and then clicks on the OK button. This input dialog box appears next. The user enters 98 and then clicks on the OK button. 3 This input dialog box appears next. The user enters 100 and then clicks on the OK button. This message dialog box appears next. The average of the three test scores is displayed. The user clicks on the OK button. This message dialog box appears next because the average is greater than 95. Figure 3-5 Interaction with the AverageScore program The code in lines 38 through 40 cause the congratulatory message to be printed: if(average>95) JOptionPane.showMessageDialog(null, That'sagreatscore!); Figure 3-6 shows the logic of this if statement. Table 3-3 shows other examples of if statements and their outcomes. Figure 3-6 Logic of the if statement 124 Chapter 3 Table 3-3 Decision Structures Other examples of if statements Statement if(hours>40) overTime=true; if(value<32) System.out.println(Invalidnumber); Outcome If hours is greater than 40, assigns true to the boolean variable overTime. If value is less than 32, displays the message Invalid number Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one long statement. For instance, the following if statements are identical except for the style in which they are written: if(value>32) System.out.println(Invalidnumber.); if(value>32)System.out.println(Invalidnumber.); In both of these examples, the compiler considers the if statement and the conditionally executed statement as one unit, with a semicolon properly placed at the end. Indentions and spacing are for the human readers of a program, not the compiler. Here are two important style rules you should adopt for writing if statements: The conditionally executed statement should appear on the line after the if statement. The conditionally executed statement should be indented one level from the if statement. In most editors, each time you press the tab key, you are indenting one level. By indenting the conditionally executed statement, you are causing it to stand out visually. This is so you can tell at a glance what part of the program the if statement executes. This is a standard way of writing if statements and is the method you should use. Be Careful with Semicolons You do not put a semicolon after the if (expression) portion of an if statement, as illustrated in Figure 3-7. This is because the if statement isnt complete without its conditionally executed statement. Figure 3-7 Do not prematurely terminate an if statement with a semicolon The if Statement 125 If you prematurely terminate an if statement with a semicolon, the compiler will not display an error message, but will assume that you are placing a null statement there. The null statement, which is an empty statement that does nothing, will become the conditionally executed statement. The statement that you intended to be conditionally executed will be disconnected from the if statement and will always execute. For example, look at the following code: intx=0,y=10; //Thefollowingifstatementisprematurely //terminatedwithasemicolon. if(x>y); System.out.println(x+isgreaterthan+y); 3 The if statement in this code is prematurely terminated with a semicolon. Because the println statement is not connected to the if statement, it will always execute. Having Multiple Conditionally Executed Statements The previous examples of the if statement conditionally execute a single statement. The if statement can also conditionally execute a group of statements, as long as they are enclosed in a set of braces. Enclosing a group of statements inside braces creates a block of statements. Here is an example: if(sales>50000) { bonus=500.0; commissionRate=0.12; daysOff+=1; } If sales is greater than 50,000, this code will execute all three of the statements inside the braces, in the order they appear. If the braces were accidentally left out, however, the if statement conditionally executes only the very next statement. Figure 3-8 illustrates this. Figure 3-8 An if statement missing its braces 126 Chapter 3 Decision Structures Flags A flag is a boolean variable that signals when some condition exists in the program. When the flag variable is set to false, it indicates the condition does not yet exist. When the flag variable is set to true, it means the condition does exist. For example, suppose a program similar to the previous test averaging program has a boolean variable named highScore. The variable might be used to signal that a high score has been achieved by the following code. if(average>95) highScore=true; Later, the same program might use code similar to the following to test the highScore variable, in order to determine if a high score has been achieved. if(highScore) System.out.println(That'sahighscore!); You will find flag variables useful in many circumstances, and we will come back to them in future chapters. Comparing Characters You can use the relational operators to test character data as well as numbers. For example, assuming that ch is a char variable, the following code segment uses the == operator to compare it to the character A. if(ch=='A') System.out.println("TheletterisA."); The != operator can also be used with characters to test for inequality. For example, the following statement determines whether the char variable ch is not equal to the letter A. if(ch!='A') System.out.println("NottheletterA."); You can also use the >, <, >=, and <= operators to compare characters. Computers do not actually store characters, such as A, B, C, and so forth, in memory. Instead, they store numeric codes that represent the characters. Recall from Chapter 2 that Java uses Unicode, which is a set of numbers that represents all the letters of the alphabet (both lower- and uppercase), the printable digits 0 through 9, punctuation symbols, and special characters. When a character is stored in memory, it is actually the Unicode number that is stored. When the computer is instructed to print the value on the screen, it displays the character that corresponds with the numeric code. The if Statement 127 Note: Unicode is an international encoding system that is extensive enough to represent all the characters of all the worlds alphabets. In Unicode, letters are arranged in alphabetic order. Because A comes before B, the numeric code for the character A is less than the code for the character B. (The code for A is 65 and the code for B is 66. Appendix A on the Student CD lists the codes for all of the printable English characters.) In the following if statement, the boolean expression 'A'<'B' is true. if('A'<'B') System.out.println(AislessthanB.); 3 In Unicode, the uppercase letters come before the lowercase letters, so the numeric code for A (65) is less than the numeric code for a (97). In addition, the space character (code 32) comes before all the alphabetic characters. Checkpoint 3.1 3.2 3.3 3.4 3.5 3.6 3.7 Write an if statement that assigns 0 to x when y is equal to 20. Write an if statement that multiplies payRate by 1.5 if hours is greater than 40. Write an if statement that assigns 0.2 to commission if sales is greater than or equal to 10000. Write an if statement that sets the variable fees to 50 if the boolean variable max is true. Write an if statement that assigns 20 to the variable y and assigns 40 to the variable z if the variable x is greater than 100. Write an if statement that assigns 0 to the variable b and assigns 1 to the variable c if the variable a is less than 10. Write an if statement that displays Goodbye if the variable myCharacter contains the character 'D'. 128 Chapter 3 Decision Structures 3.2 The if-else Statement The if-else statement is an expansion of the if statement. Here is its format: if(BooleanExpression) statementorblock else statementorblock CONCEPT THE ITS if-else STATEMENT WILL EXEEXPRESSION IS CUTE ONE GROUP OF STATEMENTS IF boolean OR ANOTHER GROUP IF ITS EXPRESSION IS true, boolean Like the if statement, a boolean expression is evaluated. If the expression is true, a statement or block of statements is executed. If the expression is false, however, a separate group of statements is executed. The program in Code Listing 3-2 uses the if-else statement to handle a classic programming problem: division by zero. In Java, a program crashes when it divides an integer by 0. When a floating-point value is divided by 0, the program doesnt crash. Instead, the special value Infinity is produced as the result of the division. Code Listing 3-2 (Division.java) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import java.util.Scanner; // Needed for the Scanner class /** This program demonstrates the if-else statement. */ public class Division { public static void main(String[] args) { double number1, number2; // Division operands double quotient; // Result of division // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get the first number. System.out.print(Enter a number: ); number1 = keyboard.nextDouble(); // Get the second number. System.out.print(Enter another number: ); number2 = keyboard.nextDouble(); false. The if-else Statement 129 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 if (number2 == 0) { System.out.println(Division by zero is not possible.); System.out.println(Please run the program again and ); System.out.println(enter a number other than zero.); } else { quotient = number1 / number2; System.out.print(The quotient of + number1); System.out.print( divided by + number2); System.out.println( is + quotient); } } } 3 Program Output with Example Input Shown in Bold Enteraninteger:10 [Enter] Enteranotherinteger:0 [Enter] Divisionbyzeroisnotpossible. Pleaseruntheprogramagainand enteranumberotherthanzero. Program Output with Example Input Shown in Bold Enteraninteger:10 [Enter] Enteranotherinteger:5 [Enter] Thequotientof10dividedby5is2.0 The value of number2 is tested before the division is performed. If the user entered 0, the block of statements controlled by the if clause executes, displaying a message which indicates the program cannot perform division by zero. Otherwise, the else clause takes control, which divides number1 by number2 and displays the result. Figure 3-9 shows the logic of the if-else statement. Figure 3-9 Logic of the if-else statement 130 Chapter 3 Decision Structures Checkpoint 3.8 3.9 Write an if-else statement that assigns 20 to the variable y if the variable x is greater than 100. Otherwise, it should assign 0 to the variable y. Write an if-else statement that assigns 1 to x when y is equal to 100. Otherwise it should assign 0 to x. sales is greater than or equal to 50000.0, in which case it assigns 0.2 to commission. 3.10 Write an if-else statement that assigns 0.10 to commission unless 3.11 Write an if-else statement that assigns 0 to the variable b and assigns 1 to the variable c if the variable a is less than 10. Otherwise, it should assign 99 to the variable b and assign 0 to the variable c. 3.3 The if-else-if Statement We make certain mental decisions by using sets of different but related rules. For example, we might decide the type of coat or jacket to wear by consulting the following rules: If it is very cold, wear a heavy coat, else, if it is chilly, wear a light jacket, else, if it is windy wear a windbreaker, else, if it is hot, wear no jacket. CONCEPT THE CHAIN OF if-else-if STATEMENT IS A if-else STATEMENTS. EACH STATEMENT IN THE CHAIN PERFORMS ITS TEST UNTIL ONE OF THE TESTS IS FOUND TO BE true. The purpose of these rules is to decide on one type of outer garment to wear. If it is cold, the first rule dictates that a heavy coat must be worn. All the other rules are then ignored. If the first rule doesnt apply (if it isnt cold), then the second rule is consulted. If that rule doesnt apply, the third rule is consulted, and so forth. The way these rules are connected is very important. If they were consulted individually, we might go out of the house wearing the wrong jacket or, possibly, more than one jacket. For instance, if it is windy, the third rule says to wear a windbreaker. What if it is both windy and very cold? Will we wear a windbreaker? A heavy coat? Both? Because of the order that the rules are consulted in, the first rule will determine that a heavy coat is needed. The third rule will not be consulted, and we will go outside wearing the most appropriate garment. This type of decision making is also very common in programming. In Java it is accomplished through the if-else-if statement. Here is the general format: The if-else-if Statement 131 if(BooleanExpression) statementorblock elseif(BooleanExpression) statementorblock // //Putasmanyelseifstatementsasneededhere. // else statementorblock This construction is actually a chain of if-else statements connected together. The else clause of one statement is linked to the if clause of another. When put together this way, the ifelse chain becomes one long statement. Notice that an else clause appears at the end. This else clause is optional, and when it is used it is known as the trailing else. It executes its statement(s) when none of the if statements above it have a boolean expression that is true. Code Listing 3-3 shows an example. The TestResults program asks the user to enter a numeric test score. It then uses an if-else-if construct to display a letter grade (A, B, C, D, or F). Figures 3-10, 3-11, and 3-12 shows what happens during three different sessions with the program. Code Listing 3-3 (TestResults.java) 1 import javax.swing.JOptionPane; // Needed for JOptionPane 2 3 /** 4 This program asks the user to enter a numeric test 5 score and displays a letter grade for the score. The 6 program displays an error message if an invalid 7 numeric score is entered. 8 */ 9 10 public class TestResults 11 { 12 public static void main(String[] args) 13{ 14inttestScore;//Numerictestscore 15Stringinput;//Toholdtheuser'sinput 16 17//Getthenumerictestscore. 18input=JOptionPane.showInputDialog(Enteryournumeric+ 19testscoreandIwilltellyouthegrade:); 20testScore=Integer.parseInt(input); 21 22//Displaythegrade. 23if(testScore<60) 3 132 Chapter 3 Decision Structures 24JOptionPane.showMessageDialog(null,YourgradeisF.); 25elseif(testScore<70) 26JOptionPane.showMessageDialog(null,YourgradeisD.); 27elseif(testScore<80) 28JOptionPane.showMessageDialog(null,YourgradeisC.); 29elseif(testScore<90) 30JOptionPane.showMessageDialog(null,YourgradeisB.); 31elseif(testScore<=100) 32JOptionPane.showMessageDialog(null,YourgradeisA.); 33else//Invalidscore 34JOptionPane.showMessageDialog(null,Invalidscore.); 35 36System.exit(0); 37} 38} This input dialog box appears first. The user enters 80 and then clicks on the OK button. This message dialog box appears next. Figure 3-10 Interaction with the TestResults program This input dialog box appears first. The user enters 72 and then clicks on the OK button. This message dialog box appears next. Figure 3-11 Interaction with the TestResults program The if-else-if Statement 133 This input dialog box appears first. The user enters 110 and then clicks on the OK button. This message dialog box appears next. 3 Figure 3-12 Interaction with the TestResults program Lets take a closer look at the if-else-if statement in lines 23 through 34. First, the relational expression score<60 is tested. if(testScore<60) JOptionPane.showMessageDialog(null,YourgradeisF.); elseif(testScore<70) JOptionPane.showMessageDialog(null,YourgradeisD.); elseif(testScore<80) JOptionPane.showMessageDialog(null,YourgradeisC.); elseif(testScore<90) JOptionPane.showMessageDialog(null,YourgradeisB.); elseif(testScore<=100) JOptionPane.showMessageDialog(null,YourgradeisA.); else//Invalidscore JOptionPane.showMessageDialog(null,Invalidscore.); If score is not less than 60, the else clause takes over and causes the next if statement to be executed. if(testScore<60) JOptionPane.showMessageDialog(null,YourgradeisF.); elseif(testScore<70) JOptionPane.showMessageDialog(null,YourgradeisD.); elseif(testScore<80) JOptionPane.showMessageDialog(null,YourgradeisC.); elseif(testScore<90) JOptionPane.showMessageDialog(null,YourgradeisB.); elseif(testScore<=100) 134 Chapter 3 Decision Structures JOptionPane.showMessageDialog(null,YourgradeisA.); else//Invalidscore JOptionPane.showMessageDialog(null,Invalidscore.); The first if statement filtered out all of the grades less than 60, so when this if statement executes, score will have a value of 60 or greater. If score is less than 70, the message Your grade is D is displayed and the rest of the if-else-if statement is ignored. This chain of events continues until one of the boolean expressions is true or the end of the statement is encountered. The trailing else catches any value that falls through the cracks. It displays an error message when none of the if statements have a boolean expression that is true. In this case, the message Invalid score is displayed. The program resumes at the statement immediately following the if-else-if statement, which is the System.exit(0) statement. Figure 3-13 shows the logic of the if-else-if statement. False score < 60 True True False score < 70 True Display "Your grade is F." False score < 80 True Display "Your grade is D." False score < 90 True Display "Your grade is C." False score <= 100 Display "Your grade is B." Display "Invalid score." Display "Your grade is A." Figure 3-13 Logic of the if-else-if statement Each if statement in the structure depends on all the boolean expressions in the if statements before it being false. To demonstrate how this interconnection works, lets look at the following code, which uses independent if statements instead of an if-else-if statement. In The if-else-if Statement 135 this code, all of the if statements execute because they are individual statements. For example, lets assume that testScore has been assigned the value 40. Because testScore is less than 60, the first if statement displays the message Your grade is F. if(testScore<60) JOptionPane.showMessageDialog(null,YourgradeisF.); if(testScore<70) JOptionPane.showMessageDialog(null,YourgradeisD.); if(testScore<80) JOptionPane.showMessageDialog(null,YourgradeisC.); if(testScore<90) JOptionPane.showMessageDialog(null,YourgradeisB.); if(testScore<=100) JOptionPane.showMessageDialog(null,YourgradeisA.); else//Invalidscore JOptionPane.showMessageDialog(null,Invalidscore.); 3 However, because the next if statement is not connected to the first through an else, it executes as well. Because testScore is less than 70, this if statement displays the message Your grade is D. Likewise the next if statement executes and displays the message Your grade is C. This will continue until all the if statements have executed. 136 Chapter 3 Decision Structures Checkpoint 3.12 What will the following program display? publicclassCheckPoint { publicstaticvoidmain(String[]args) { intfunny=7,serious=15; funny=serious%2; if(funny!=1) { funny=0; serious=0; } elseif(funny==2) { funny=10; serious=10; } else { funny=1; serious=1; } System.out.println(funny++serious); } } 3.13 The following program is used in a bookstore to determine how many discount coupons a customer gets. Complete the table that appears after the program. importjavax.swing.JOptionPane; publicclassCheckPoint { publicstaticvoidmain(String[]args) { intbooks,coupons; Stringinput; Nested if Statements 137 input=JOptionPane.showInputDialog(Howmanybooks+ arebeingpurchased?); books=Integer.parseInt(input); if(books<1) coupons=0; elseif(books<3) coupons=1; elseif(books<5) coupons=2; else coupons=3; JOptionPane.showMessageDialog(null, Thenumberofcouponstogiveis+ coupons); System.exit(0); } } 3 If the customer purchases this many books... 1 2 3 4 5 10 this many coupons are given. 3.4 Nested if Statements Anytime an if statement appears inside another, it is conCONCEPT sidered nested. In actuality, the if-else-if structure is a nested if statement. Each if (after the first one) is nested A NESTED if STATEMENT IS AN if in the else part of the previous if. STATEMENT IN THE CONDITIONALLY Code Listing 3-4 shows a program with a nested if stateEXECUTED CODE OF ANOTHER if ment. Suppose the program is used to determine whether a STATEMENT. bank customer qualifies for a loan. To qualify, a customer must earn at least $30,000 per year, and must have been on his or her current job for at least two years. Figures 3-14, 3-15, and 3-16 show what happens during three different sessions with the program. 138 Chapter 3 Decision Structures Code Listing 3-4 (LoanQualifier.java) 1 import javax.swing.JOptionPane; // Needed for JOptionPane class 2 3 /** 4 This program demonstrates a nested if statement. 5 **/ 6 7 public class LoanQualifier 8 { 9 public static void main(String[] args) 10 { 11 double salary; // Annual salary 12 double yearsOnJob; // Years at current job 13 String input; // To hold string input 14 15//Gettheuser'sannualsalary. 16input=JOptionPane.showInputDialog(Enteryour+ 17annualsalary.); 18salary=Double.parseDouble(input); 19 20//Getthenumberofyearsatthecurrentjob. 21input=JOptionPane.showInputDialog(Enterthenumberof+ 22yearsatyourcurrentjob.); 23yearsOnJob=Double.parseDouble(input); 24 25//Determinewhethertheuserqualifiesfortheloan. 26if(salary>=30000) 27{ 28if(yearsOnJob>=2) 29{ 30JOptionPane.showMessageDialog(null,Youqualify+ 31fortheloan.); 32} 33else 34{ 35JOptionPane.showMessageDialog(null,Youmusthave+ 36beenonyourcurrentjobforatleast+ Nested if Statements 139 37twoyearstoqualify.); 38} 39} 40else 41{ 42JOptionPane.showMessageDialog(null,Youmustearn+ 43atleast$30,000peryeartoqualify.); 44} 45 46System.exit(0); 47} 48} 3 This input dialog box appears first. The user enters 35000 and clicks on the OK button. This input dialog box appears next. The user enters 1 and clicks on the OK button. This message dialog box appears next. Figure 3-14 Interaction with the LoanQualifier program 140 Chapter 3 Decision Structures This input dialog box appears first. The user enters 25000 and clicks on the OK button. This input dialog box appears next. The user enters 5 and clicks on the OK button. This message dialog box appears next. Figure 3-15 Interaction with the LoanQualifier program This input dialog box appears first. The user enters 35000 and clicks on the OK button. This input dialog box appears next. The user enters 5 and clicks on the OK button. This message dialog box appears next. Figure 3-16 Interaction with the LoanQualifier program The first if statement conditionally executes the second one. The only way the program will execute the second if statement is for the salary variable to contain a value that is greater than or equal to 30,000. When this is the case, the second if statement will test the yearsOnJob Nested if Statements 141 variable. If it contains a value that is greater than or equal to 2, a dialog box will be displayed informing the user that he or she qualifies for the loan. Figure 3-17 shows the logic of the if statements. 3 Figure 3-17 Logic of the nested if statements We should note that the braces used in the if statements in this program are not required. They could have been written this way: if(salary>=30000) if(yearsOnJob>=2) JOptionPane.showMessageDialog(null,Youqualify+ fortheloan.); else JOptionPane.showMessageDialog(null,Youmusthave+ beenonyourcurrentjobforatleast+ twoyearstoqualify.); else JOptionPane.showMessageDialog(null,Youmustearn+ atleast$30,000peryeartoqualify.); Not only do the braces make the statements easier to read, but they also help in debugging code. When debugging a program with nested if-else statements, its important to know which if clause each else clause belongs to. The rule for matching else clauses with if clauses is this: 142 Chapter 3 Decision Structures An else clause goes with the closest previous if clause that doesnt already have its own else clause. This is easy to see when the conditionally executed statements are enclosed in braces and are properly indented, as illustrated in Figure 3-18. Each else clause lines up with the if clause it belongs to. These visual cues are important because nested if statements can be very long and complex. Figure 3-18 Alignment of if and else clauses Checkpoint 3.14 Write nested if statements that perform the following test: If amount1 is greater than 10 and amount2 is less than 100, display the greater of the two. 3.15 Write code that tests the variable x to determine if it is greater than 0. If x is greater than 0, the code should test the variable y to determine if it is less than 20. If y is less than 20, the code should assign 1 to the variable z. If y is not less than 20, the code should assign 0 to the variable z. 3.5 Logical Operators Java provides two binary logical operators, && and ||, which are used to combine two boolean expressions into a single expression. It also provides the unary ! operator, which reverses the truth of a boolean expression. Table 3-4 describes these logical operators. CONCEPT LOGICAL OPERATORS CONNECT TWO OR MORE RELATIONAL EXPRESSIONS INTO ONE OR REVERSE THE LOGIC OF AN EXPRESSION. Logical Operators 143 Table 3-4 Logical operators Operator && || Meaning AND OR Effect Connects two boolean expressions into one. Both expressions must be true for the overall expression to be true. Connects two boolean expressions into one. One or both expressions must be true for the overall expression to be true. It is only necessary for one to be true, and it does not matter which one. The ! operator reverses the truth of a boolean expression. If it is applied to an expression that is true, the operator returns false. If it is applied to an expression that is false, the operator returns true. ! NOT 3 Table 3-5 shows examples of several boolean expressions that use logical operators. Table 3-5 boolean expressions using logical operators Expression x>y&&a<b x==y||x==z !(x>y) Meaning Is x greater than y AND is a less than b? Is x equal to y OR is x equal to z? Is the expression x > y NOT true? Lets take a close look at each of these operators. The && Operator The && operator is known as the logical AND operator. It takes two boolean expressions as operands and creates a boolean expression that is true only when both subexpressions are true. Here is an example of an if statement that uses the && operator: if(temperature<20&&minutes>12) { System.out.println(Thetemperatureisinthe+ dangerzone.); } In this statement the two boolean expressions temperature<20 and minutes>12 are combined into a single expression. The message will only be displayed if temperature is less than 20 AND minutes is greater than 12. If either boolean expression is false, the entire expression is false and the message is not displayed. 144 Chapter 3 Decision Structures Table 3-6 shows a truth table for the && operator. The truth table lists expressions showing all the possible combinations of true and false connected with the && operator. The resulting values of the expressions are also shown. Table 3-6 Truth table for the && operator Expression true&&false false&&true false&&false true&&true Value of the Expression false false false true As the table shows, both sides of the && operator must be true for the operator to return a true value. The && operator performs short-circuit evaluation. Heres how it works: If the expression on the left side of the && operator is false, the expression on the right side will not be checked. Because the entire expression is false if only one of the subexpressions is false, it would waste CPU time to check the remaining expression. So, when the && operator finds that the expression on its left is false, it short-circuits and does not evaluate the expression on its right. The && operator can be used to simplify programs that otherwise would use nested if statements. The program in Code Listing 3-5 is a different version of the LoanQualifier program in Code Listing 3-4, written to use the && operator. Figures 3-19 and 3-20 show the interaction during two different sessions with the program. Code Listing 3-5 (LogicalAnd.java) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import javax.swing.JOptionPane; /** This program demonstrates the logical && operator. */ public class LogicalAnd { public static void main(String[] args) { double salary; // Annual salary double yearsOnJob; // Years at current job String input; // To hold string input // Needed for JOptionPane class Logical Operators 145 15 // Get the users annual salary. 16input=JOptionPane.showInputDialog(Enteryour+ 17annualsalary.); 18salary=Double.parseDouble(input); 19 20//Getthenumberofyearsatthecurrentjob. 21input=JOptionPane.showInputDialog(Enterthenumberof+ 22yearsatyourcurrentjob.); 23yearsOnJob=Double.parseDouble(input); 24 25//Determinewhethertheuserqualifiesfortheloan. 26if(salary>=30000&&yearsOnJob>=2) 27{ 28JOptionPane.showMessageDialog(null,Youqualify+ 29fortheloan.); 30} 31else 32{ 33JOptionPane.showMessageDialog(null,Youdonot+ 34qualifyfortheloan.); 35} 36 37System.exit(0); 38} 39} 3 This input dialog box appears first. The user enters 50000 and clicks on the OK button. This input dialog box appears next. The user enters 1 and clicks on the OK button. This message dialog box appears next. Figure 3-19 Interaction with the LogicalAnd program 146 Chapter 3 Decision Structures This input dialog box appears first. The user enters 50000 and clicks on the OK button. This input dialog box appears next. The user enters 4 and clicks on the OK button. This message dialog box appears next. Figure 3-20 Interaction with the LogicalAnd program The message Youqualifyfortheloan. is displayed only when both the expressions salary>=30000 andyearsOnJob>=2 are true.If either of these expressions is false, the message Youdonotqualifyfortheloan. is displayed. You can also use logical operators with boolean variables. For example, assuming that isValid is a boolean variable, the following if statement determines whether isValid is true and x is greater than 90. if(isValid&&x>90) The || Operator The || operator is known as the logical OR operator. It takes two boolean expressions as operands and creates a boolean expression that is true when either of the subexpressions are true. Here is an example of an if statement that uses the || operator: if(temperature<20||temperature>100) { System.out.println(Thetemperatureisinthe+ dangerzone.); } The message will be displayed if temperature is less than 20 OR temperature is greater than 100. If either relational test is true,the entire expression is true. Table 3-7 shows a truth table for the || operator. Logical Operators 147 Table 3-7 Truth table for the || operator Expression true||false false||true false||false true||true Value true true false true All it takes for an OR expression to be true is for one side of the || operator to be true. It doesnt matter if the other side is false or true. Like the &&operator, the || operator performs short-circuit evaluation. If the expression on the left side of the || operator is true, the expression on the right side will not be checked. Because it is only necessary for one of the expressions to be true,it would waste CPU time to check the remaining expression. The program in Code Listing 3-6 is a different version of the previous program, shown in Code Listing 3-5. This version uses the || operator to determine whether salary>=30000 is true OR yearsOnJob>=2 is true. If either expression is true, then the person qualifies for the loan. Figure 3-21 shows example interaction with the program. Code Listing 3-6 (LogicalOr.java) 1 import javax.swing.JOptionPane; // Needed for JOptionPane class 2 3 /** 4 This program demonstrates the logical || operator. 5 */ 6 7 public class LogicalOr 8 { 9 public static void main(String[] args) 10 { 11 double salary; // Annual salary 12 double yearsOnJob; // Years at current job 13 String input; // To hold string input 14 15//Gettheuser'sannualsalary. 16input=JOptionPane.showInputDialog(Enteryour+ 17annualsalary.); 18salary=Double.parseDouble(input); 19 20//Getthenumberofyearsatthecurrentjob. 3 148 Chapter 3 Decision Structures 21input=JOptionPane.showInputDialog(Enterthenumberof+ 22yearsatyourcurrentjob.); 23yearsOnJob=Double.parseDouble(input); 24 25//Determinewhethertheuserqualifiesforloan. 26if(salary>=30000||yearsOnJob>=2) 27{ 28JOptionPane.showMessageDialog(null,Youqualify+ 29fortheloan.); 30} 31else 32{ 33JOptionPane.showMessageDialog(null,Youdonot+ 34qualifyfortheloan.); 35} 36 37System.exit(0); 38} 39} This input dialog box appears first. The user enters 20000 and clicks on the OK button. This input dialog box appears next. The user enters 7 and clicks on the OK button. This message dialog box appears next. Figure 3-21 Interaction with the LogicalOr program The ! Operator The ! operator performs a logical NOT operation. It is a unary operator that takes a boolean expression as its operand and reverses its logical value. In other words, if the expression is true,the ! operator returns false, and if the expression is false, it returns true. Here is an if statement using the ! operator: Logical Operators 149 if(!(temperature>100)) System.out.println(Thisisbelowthemaximumtemperature.); First, the expression (temperature>100) is tested and a value of either true or false is the result. Then the ! operator is applied to that value. If the expression (temperature>100) is true, the ! operator returns false. If the expression (temperature>100) is false, the ! operator returns true. The previous code is equivalent to asking: Is the temperature not greater than 100? Table 3-8 shows a truth table for the ! operator. Table 3-8 Truth table for the ! operator 3 Expression !true !false Value false true The Precedence and Associativity of Logical Operators Like other operators, the logical operators have orders of precedence and associativity. Table 3-9 shows the precedence of the logical operators, from highest to lowest. Table 3-9 Logical operators in order of precedence ! && || The ! operator has a higher precedence than many of Javas other operators. You should always enclose its operand in parentheses unless you intend to apply it to a variable or a simple expression with no other operators. For example, consider the following expressions (assume x is an int variable with a value stored in it): !(x>2) !x>2 150 Chapter 3 Decision Structures The first expression applies the ! operator to the expression x>2. It is asking is x not greater than 2? The second expression, however, attempts to apply the ! operator to x only. It is asking is the logical compliment of x greater than 2? Because the ! operator can only be applied to boolean expressions, this statement would cause a compiler error. The && and || operators rank lower in precedence than the relational operators, so precedence problems are less likely to occur. If you are unsure, however, it doesnt hurt to use parentheses anyway. (a>b)&&(x<y)is the same asa>b&&x<y (x==y)||(b>a)is the same asx==y||b>a The logical operators evaluate their expressions from left to right. In the following expression, a<b is evaluated before y==z. a<b||y==z In the following expression, y==z is evaluated first, however, because the && operator has higher precedence than ||. a<b||y==z&&m>j This expression is equivalent to: (a<b)||((y==z)&&(m>j)) Table 3-10 shows the precedence of all the operators we have discussed so far. This table includes the assignment, arithmetic, relational, and logical operators. Table 3-10 Precedence of all operators discussed so far Order of Precedence Operators 1 2 3 4 5 6 7 8 - (unary negation) ! */% +<><=>= ==!= && || =+=-=*=/=%= Description Unary negation, logical not Multiplication, division, modulus Addition, subtraction Less than, greater than, less than or equal to, greater than or equal to Equal to, not equal to Logical AND Logical OR Assignment and combined assignment Logical Operators 151 Checking Numeric Ranges with Logical Operators Sometimes you will need to write code that determines whether a numeric value is within a specific range of values or outside a specific range of values. When determining whether a number is inside a range, its best to use the && operator. For example, the following if statement checks the value in x to determine if it is in the range of 20 through 40: if(x>=20&&x<=40) System.out.println(x+isintheacceptablerange.); The boolean expression in the if statement will be true only when x is greater than or equal to 20 AND less than or equal to 40. The value in x must be within the range of 20 through 40 for this expression to be true. When determining whether a number is outside a range, the || operator is best to use. The following statement determines whether x is outside the range of 20 through 40: if(x<20||x>40) System.out.println(x+isoutsidetheacceptablerange.); 3 Its important not to get the logic of these logical operators confused. For example, the boolean expression in the following if statement would never test true: if(x<20&&x>40) System.out.println(x+isoutsidetheacceptablerange.); Obviously, x cannot be less than 20 and at the same time be greater than 40. 152 Chapter 3 Decision Structures Checkpoint 3.16 The following truth table shows various combinations of the values true and false connected by a logical operator. Complete the table by indicating if the result of such a combination is true or false. Logical Expression true&&false true&&true false&&true false&&false true||false true||true false||true false||false !true !false Result (true or false) 3.17 Assume the variables a = 2, b = 4, and c = 6. Indicate by circling the T or F if each of the following conditions is true or false. a==4||b>2 T 6<=c&&a>3 T 1!=b&&c!=3 T a>=-1||a<=b T !(a>2) T F F F F F 3.18 Write an if statement that displays the message The number is valid if the variable speed is within the range 0 through 200. 3.19 Write an if statement that displays the message The number is not valid if the variable speed is outside the range 0 through 200. 3.6 Comparing String Objects You saw in the preceding sections how numeric values can be compared using the relational operators. You should not use the relational operators to compare String objects, however. Remember that a String object is referenced by a variable that contains the objects memory address. When you use a relational operator with the reference variable, the operator works on the memory address that the variable contains, not the contents of the String object. For example, suppose a program has the following declarations: CONCEPT YOU CANNOT USE RELATIONAL OPERATORS TO COMPARE String OBJECTS. INSTEAD YOU MUST USE A String METHOD. Comparing String Objects 153 Stringname1=Mark; Stringname2=Mary; And later, the same program has the following if statement: if(name1==name2) The expression name1==name2 will be false, but not because the strings Mark and Mary are different. The expression will be false Figure 3-22 The name1 and name2 variables reference because the variables name1 and different String objects name2 reference different objects. Figure 3-22 illustrates how the variables reference the String objects. To correctly compare the contents of two String objects, you should use the String classs equals method. The general form of the method is: StringReference1.equals(StringReference2) StringReference1 is a variable that references a String object, and StringReference2 is another variable that references a String object. The method returns true if the two strings are equal, or false if they are not equal. Here is an example: if(name1.equals(name2)) 3 Assuming that name1 and name2 reference String objects, the expression in the if statement will return true if they are the same, or false if they are not the same. The program in Code Listing 3-7 demonstrates. Code Listing 3-7 (StringCompare.java) 1/** 2ThisprogramcorrectlycomparestwoStringobjectsusing 3theequalsmethod. 4*/ 5 6publicclassStringCompare 7{ 8publicstaticvoidmain(String[]args) 9{ 10Stringname1=Mark, 11name2=Mark, 12name3=Mary; 13 154 Chapter 3 Decision Structures 14//CompareMarkandMark 15 16if(name1.equals(name2)) 17{ 18System.out.println(name1+and+name2+ 19arethesame.); 20} 21else 22{ 23System.out.println(name1+and+name2+ 24areNOTthesame.); 25} 26 27//CompareMarkandMary 28 29if(name1.equals(name3)) 30{ 31System.out.println(name1+and+name3+ 32arethesame.); 33} 34else 35{ 36System.out.println(name1+and+name3+ 37areNOTthesame.); 38} 39} 40} Program Output MarkandMarkarethesame. MarkandMaryareNOTthesame. You can also compare String objects to string literals. Simply pass the string literal as the argument to the equals method, as shown here: if(name1.equals(Mark)) To determine if two strings are not equal, simply apply the ! operator to the equals methods return value. Here is an example: if(!name1.equals(Mark)) The boolean expression in this if statement performs a not-equal-to operation. It determines whether the object referenced by name1 is not equal to Mark. Comparing String Objects 155 The String class also provides the compareTo method, which can be used to determine whether one string is greater than, equal to, or less than another string. The general form of the method is: StringReference.compareTo(OtherString) StringReference is a variable that references a String object, and OtherString is either another variable that references a String object or a string literal. The method returns an integer value that can be used in the following manner: If the methods return value is negative, the string referenced by StringReference (the calling object) is less than the OtherString argument. If the methods return value is 0, the two strings are equal. If the methods return value is positive, the string referenced by StringReference (the calling object) is greater than the OtherString argument. For example, assume that name1 and name2 are variables that reference String objects. The following if statement uses the compareTo method to compare the strings. if(name1.compareTo(name2)==0) System.out.println(Thenamesarethesame.); 3 Also, the following expression compares the string referenced by name1 to the string literal Joe. if(name1.compareTo(Joe)==0) System.out.println(Thenamesarethesame.); The program in Code Listing 3-8 more fully demonstrates the compareTo method. Code Listing 3-8 (StringCompareTo.java) 1/** 2ThisprogramcomparestwoStringobjectsusing 3thecompareTomethod. 4*/ 5 6publicclassStringCompareTo 7{ 8publicstaticvoidmain(String[]args) 9{ 10Stringname1=Mary, 11name2=Mark; 12 13//CompareMaryandMark 14 156 Chapter 3 Decision Structures 15if(name1.compareTo(name2)<0) 16{ 17System.out.println(name1+islessthan+name2); 18} 19elseif(name1.compareTo(name2)==0) 20{ 21System.out.println(name1+isequalto+name2); 22} 23elseif(name1.compareTo(name2)>0) 24{ 25System.out.println(name1+isgreaterthan+name2); 26} 27} 28} Program Output MaryisgreaterthanMark Lets take a closer look at this program. When you use compareTo the method to compare two strings, the strings are compared character by character. This is often called a lexicographical comparison. The program uses the compareTo method to compare the strings Mary and Mark, beginning with the first, or leftmost, characters. This is illustrated in Figure 3-23. Here is how the comparison takes place: 1. The M in Mary is compared with the M in Mark. Because these are the same, the next characters are compared. 2. The a in Mary is compared with the a in Mark. Because these are the same, the next characters are compared. 3. The r in Mary is compared with the r in Mark. Because these are the same, the next characters are compared. 4. The y in Mary is compared with the k in Mark. Because these are not the same, the two strings are not equal. The character y is greater than k, so it is determined that Mary is greater than Mark. If one of the strings in a comparison is shorter in length than the other, Java can only compare the corresponding characters. If the corresponding characters are identical, then the shorter string is considered less than the longer string. For example, suppose the strings High and Hi were being compared. The string Hi would be considered less than High because it is shorter in length. Comparing String Objects 157 Ignoring Case in String Comparisons The equals and compareTo methods perform case sensitive comparisons, which means that uppercase letters are not considered the same as their lowercase counterparts. In other words, A is not the same as a. This can obviously lead to problems when you want to perform case insensitive comparisons. The String class provides the equalsIgnoreCase and compareToIgnoreCase methods. These methods Figure 3-23 String comparison of work like the equals and compareTo methods, except Mary and Mark the case of the characters in the strings is ignored. For example, the program in Code Listing 3-9 asks the user to enter the secret word, which is similar to a password. The secret word is PROSPERO, and the program performs a case-insensitive string comparison to determine whether the user has entered it. Code Listing 3-9 (SecretWord.java) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import java.util.Scanner; // Needed for the Scanner class /** This program demonstrates a case insensitive string comparison. */ public class SecretWord { public static void main(String[] args) { String input; // To hold the users input // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Prompt the user to enter the secret word. System.out.print(Enter the secret word: ); input = keyboard.nextLine(); // Determine whether the user entered the secret word. if (input.equalsIgnoreCase(PROSPERO)) { System.out.println(Congratulations! You know the + secret word!); } 3 158 Chapter 3 26 27 28 29 30 31 32 Decision Structures else { System.out.println(Sorry, that is NOT the + secret word!); } } } Program Output with Example Input Shown in Bold Enterthesecretword:Ferdinand [Enter] Sorry,thatisNOTthesecretword! Program Output with Example Input Shown in Bold Enterthesecretword:Prospero [Enter] Congratulations!Youknowthesecretword! The compareToIgnoreCase method works exactly like the compareTo method, except the case of the characters in the strings being compared is ignored. Checkpoint 3.20 Assume the variable name references a String object. Write an if statement that displays Do I know you? if the String object contains Timothy. 3.21 Assume the variables name1 and name2 reference two different String objects, containing different strings. Write code that displays the strings referenced by these variables in alphabetical order. 3.22 Modify the statement you wrote in response to Checkpoint 3.20 so it performs a case insensitive comparison. 3.7 More about Variable Declaration and Scope Recall from Chapter 2 that a local variable is a variable that is declared inside a method. Java allows you to create local variables just about anywhere in a method. For example, look at the program in Code Listing 3-10. The main method declares CONCEPT THE SCOPE OF A VARIABLE IS LIMITED TO THE BLOCK IN WHICH IT IS DECLARED. More about Variable Declaration and Scope 159 two String reference variables: firstName and lastName. Notice that the declarations of these variables appear near the code that first uses the variables. Code Listing 3-10 (VariableScope.java) 1 import javax.swing.JOptionPane; // Needed for JOptionPane 2 3 /** 4 This program demonstrates how variables may be declared 5 in various locations throughout a program. 6 */ 7 8publicclassVariableScope 9{ 10publicstaticvoidmain(String[]args) 11{ 12//Gettheuser'sfirstname. 13StringfirstName; 14firstName=JOptionPane.showInputDialog(Enteryour+ 15firstname.); 16 17//Gettheuser'slastname. 18StringlastName; 19lastName=JOptionPane.showInputDialog(Enteryour+ 20lastname.); 21 22JOptionPane.showMessageDialog(null,Hello+firstName+ 23+lastName); 24System.exit(0); 25} 26} 3 Although it is a common practice to declare all of a methods local variables at the beginning of the method, it is possible to declare them at later points. Sometimes programmers declare certain variables near the part of the program where they are used in order to make their purpose more evident. Recall from Chapter 2 that a variables scope is the part of the program where the variables name may be used. A local variables scope always starts at the variables declaration, and ends at the closing brace of the block of code in which it is declared. In Code Listing 3-10, the firstName variable is visible only to the code in lines 13 through 24. The lastName variable is visible only to the code in lines 18 through 24. 160 Chapter 3 Decision Structures Note: When a program is running and it enters the section of code that constitutes a variables scope, it is said that the variable comes into scope. This simply means the variable is now visible and the program may reference it. Likewise, when a variable leaves scope it may not be used. 3.8 The Conditional Operator (Optional) The conditional operator is powerful and unique. Because it takes three operands, it is considered a ternary operator. The conditional operator provides a shorthand method of expressing a simple if-else statement. The operator consists of the question mark (?) and the colon (:). Its format is: Expression1?Expression2:Expression3; CONCEPT YOU CAN USE THE CONDITIONAL OPERATOR TO CREATE SHORT EXPRESSIONS THAT WORK LIKE if-else STATEMENTS. Expression1, Expression2, and Expression3 are the three operands. Expression1 is a boolean expression, which is tested. Its like the boolean expression in the parentheses of an if statement. If Expression1 is true, then Expression2 is executed. Otherwise, Expression3 is executed. Here is an example of a statement using the conditional operator: x<0?y=10:Z=20; This statement is called a conditional expression and consists of three sub-expressions separated by the ? and : symbols. The expressions are x<0, y=10, and Z=20, as illustrated here: x<0 ? y=10 : z=20; This preceding conditional expression performs the same operation as the following ifelse statement: if(x<0) y=10; else Z=20; If it helps, you can put parentheses around the subexpressions in a conditional expression, as in the following: (x<0)?(y=10):(Z=20); The Conditional Operator (Optional) 161 Using the Value of a Conditional Expression The conditional expression also returns a value. If Expression1 is true, the value of the conditional expression is the value of Expression2. Otherwise it is the value of Expression3. Here is an example of an assignment statement using the value of a conditional expression: number=x>100?20:50; The value assigned to number will be either 20 or 50, depending upon whether x is greater than 100. This statement could be expressed as the following if-else statement: if(x>100) number=20; else number=50; 3 The conditional operator gives you the ability to pack decision-making power into a concise line of code. With a little imagination it can be applied to many other programming problems. For instance, consider the following statement: System.out.println(Yourgradeis:+ (score<60?Fail.:Pass.)); Converted to an if-elsestatement, it would be written as follows: if(score<60) System.out.println(Yourgradeis:Fail.); else System.out.println(Yourgradeis:Pass.); Note: The parentheses are placed around the conditional expression because the + operator has higher precedence than the ?: operator. Without the parentheses, the + operator would concatenate the value in score with the string Yourgradeis:. To see an example program that uses the conditional operator, see the ConsultantCharges.java program in this chapters source code folder on the Student CD. 162 Chapter 3 Decision Structures Checkpoint 3.23 Rewrite the following if-else statements as conditional expressions. A) if(x>y) z=1; else z=20; if(temp>45) population=base*10; else population=base*2; if(hours>40) wages*=1.5; else wages*=1; if(result>=0) System.out.println(Theresultispositive.); else System.out.println(Theresultisnegative.); B) C) D) 3.9 The switch Statement A branch occurs when one part of a program causes another part to execute. The if-else-if statement allows your program to branch into one of several possible paths. It tests a series of boolean expressions, and branches if one of those expressions is true. The switch statement is a similar mechanism. It, however, tests the value of an integer or character expression and then uses that value to determine which set of statements to branch to. Here is the format of the switch statement: switch(SwitchExpression) { caseCaseExpression: //placeoneormore //statementshere break; caseCaseExpression: //placeoneormore //statementshere break; //casestatementsmayberepeatedasmany //timesasnecessary default: //placeoneormore //statementshere } CONCEPT THE switch STATEMENT LETS THE VALUE OF A VARIABLE OR EXPRESSION DETERMINE WHERE THE PROGRAM WILL BRANCH TO. The switch Statement 163 The first line of the statement starts with the word switch, followed by a SwitchExpression inside parentheses. The SwitchExpression is an expression that must result in a value of one of these types: char, byte, short, or int. On the next line is the beginning of a block containing several case statements. Each case statement is formatted in the following manner: caseCaseExpression: //placeoneormore //statementshere break; The case statement starts with the keyword case, followed by a CaseExpression. The CaseExpression is a literal or a final variable which must be of the char, byte, short, or int types. The CaseExpression is followed by a colon. After the case statement, one or more valid programming statements may appear. These statements are branched to if the value of the SwitchExpression matches the case statements CaseExpression. The last statement in the group of statements should be the keyword break. The break statement causes the program to jump out of the switch statement and resume processing at the statement following it. Note: The CaseExpressions of each case statement must be unique. A default section normally comes after all the case statements. This section is branched to if none of the case expressions match the switch expression. Note: The default section is optional. If you leave it out, however, your program will have nowhere to branch to if the SwitchExpression doesnt match any of the CaseExpressions. The program in Code Listing 3-11 shows how a simple switch statement works. Code Listing 3-11 (SwitchDemo.java) 1 2 3 4 5 6 import java.util.Scanner; /** This program demonstrates the switch statement. */ // Needed for Scanner class 3 164 Chapter 3 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 Decision Structures public class SwitchDemo { public static void main(String[] args) { int number; // A number entered by the user // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get one of the numbers 1, 2, or 3 from the user. System.out.print(Enter 1, 2, or 3: ); number = keyboard.nextInt(); // Determine the number entered. switch (number) { case 1: System.out.println(You entered 1.); break; case 2: System.out.println(You entered 2.); break; case 3: System.out.println(You entered 3.); break; default: System.out.println(Thats not 1, 2, or 3!); } } } Program Output with Example Input Shown in Bold Enter1,2,or3:2 [Enter] Youentered2. Program Output with Example Input Shown in Bold Enter1,2,or3:5 [Enter] That'snot1,2,or3! The switch Statement 165 The first case statement is case 1, the second is case 2, and the third is case 3. These statements mark where the program is to branch to if the variable number contains the values 1, 2, or 3. The default section is branched to if the user enters anything other than 1, 2, or 3. Notice the break statements that are in the case1, case2, and case3sections. switch(number) { case1: System.out.println(Youentered1.); break; case2: System.out.println(Youentered2.); break; case3: System.out.println(Youentered3.); break; default: System.out.println(That'snot1,2,or3!); } 3 The case statements show the program where to start executing in the block and the break statements show the program where to stop. Without the break statements, the program would execute all of the lines from the matching case statement to the end of the block. Note: The default section (or the last case section if there is no default) does not need a break statement. Some programmers prefer to put one there anyway for consistency. The program in Code Listing 3-12 is a modification of Code Listing 3-11, without the break statements. Code Listing 3-12 (NoBreaks.java) 1 2 3 4 5 6 import java.util.Scanner; /** This program demonstrates the switch statement. */ // Needed for Scanner class 166 Chapter 3 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 Decision Structures public class NoBreaks { public static void main(String[] args) { int number; // A number entered by the user // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get one of the numbers 1, 2, or 3 from the user. System.out.print(Enter 1, 2, or 3: ); number = keyboard.nextInt(); // Determine the number entered. switch (number) { case 1: System.out.println(You entered 1.); case 2: System.out.println(You entered 2.); case 3: System.out.println(You entered 3.); default: System.out.println(Thats not 1, 2, or 3!); } } } Program Output with Example Input Shown in Bold Enter1,2,or3:1 [Enter] Youentered1. Youentered2. Youentered3. That'snot1,2,or3! Program Output with Example Input Shown in Bold Enter1,2,or3:3 [Enter] Youentered3. That'snot1,2,or3! The switch Statement 167 Without the break statement, the program falls through all of the statements below the one with the matching case expression. Sometimes this is what you want. For instance, the program in Code Listing 3-13 asks the user to select a grade of pet food. The available choices are A, B, and C. The switch statement will recognize either upper or lowercase letters. Code Listing 3-13 (PetFood.java) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import java.util.Scanner; // Needed for the Scanner class /** This program demonstrates a switch statement. */ public class PetFood { public static void main(String[] args) { String input; // To hold the users input char foodGrade; // Grade of pet food // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Prompt the user for a grade of pet food. System.out.println(Our pet food is available in + three grades:); System.out.print(A, B, and C. Which do you want + pricing for? ); input = keyboard.nextLine(); foodGrade = input.charAt(0); // Display pricing for the selected grade. switch(foodGrade) { case a: case A: System.out.println(30 cents per lb.); break; case b: case B: System.out.println(20 cents per lb.); break; 3 168 Chapter 3 36 37 38 39 40 41 42 43 44 Decision Structures case c: case C: System.out.println(15 cents per lb.); break; default: System.out.println(Invalid choice.); } } } Program Output with Example Input Shown in Bold Ourpetfoodisavailableinthreegrades: A,B,andC.Whichdoyouwantpricingfor?b [Enter] 20centsperlb. Program Output with Example Input Shown in Bold Ourpetfoodisavailableinthreegrades: A,B,andC.Whichdoyouwantpricingfor?B [Enter] 20centsperlb. When the user enters a the corresponding case has no statements associated with it, so the program falls through to the next case, which corresponds with A. case'a': case'A': System.out.println(30centsperlb.); break; The same technique is used for b and c. Checkpoint 3.24 Complete the following program skeleton by writing a switch statement that displays one if the user has entered 1, two if the user has entered 2, and three if the user has entered 3. If a number other than 1, 2, or 3 is entered, the program should display an error message. import java.util.Scanner; public class CheckPoint { public static void main(String[] args) { int userNum; The switch Statement 169 Scanner keyboard = new Scanner(System.in); System.out.print(Enter one of the numbers + 1, 2, or 3: ); userNum = keyboard.nextInt(); // // Write the switch statement here. // } } 3.25 Rewrite the following if-else-if statement as a switch statement. if(selection=='A') System.out.println(YouselectedA.); elseif(selection=='B') System.out.println(YouselectedB.); elseif(selection=='C') System.out.println(YouselectedC.); elseif(selection=='D') System.out.println(YouselectedD.); else System.out.println(Notgoodwithletters,eh?); 3 3.26 Explain why you cannot convert the following if-else-if statement into a switch statement. if(temp==100) x=0; elseif(population>1000) x=1; elseif(rate<.1) x=-1; 3.27 What is wrong with the following switch statement? //Thiscodehaserrors!!! switch(temp) { casetemp<0: System.out.println(Tempisnegative.); break; casetemp==0: System.out.println(Tempiszero.); break; casetemp>0: System.out.println(Tempispositive.); break; } 170 Chapter 3 Decision Structures 3.28 What will the following code display? intfunny=7,serious=15; funny=serious*2; switch(funny) {case0: System.out.println(Thatisfunny.); break; case30: System.out.println(Thatisserious.); break; case32: System.out.println(Thatisseriouslyfunny.); break; default: System.out.println(funny); } 3.10 Creating Objects with the DecimalFormat Class In Java, a value of the double data type can be displayed with as many as 15 decimal places, and a value of the float data type can be displayed with up to 6 decimal places. For example, look at the following code: doublenumber=10.0/6.0; System.out.println(number); CONCEPT THE DecimalFormat CLASS CAN BE USED TO FORMAT THE APPEARANCE OF FLOATING-POINT NUMBERS ROUNDED TO A SPECIFIED NUMBER OF DECIMAL PLACES. This code will display: 1.666666666666667 Quite often, you want to control the number of decimal places that are displayed. For example, when displaying dollar amounts, you normally display two decimal places. You can use the DecimalFormat class, which is part of the API, to control the way floating-point numbers are formatted. First, to use the DecimalFormat class you must have the following import statement at the top of your program: importjava.text.DecimalFormat; The DecimalFormat class is not automatically available to your Java programs. This statement makes the class available. Creating Objects with the DecimalFormat Class 171 Recall from Chapter 2s discussion of the String class that a class is a description of an object. It specifies the attributes and methods that an object has. In this book, a class is frequently referred to as a blueprint that objects may be created from. When a program is running, it can use a class to create, in memory, as many objects as needed. Each object that is created from a class is called an instance of the class. To use the DecimalFormat class, you create an object, or an instance, of the class. The following statement shows an example. DecimalFormatformatter=newDecimalFormat(#0.00); Lets dissect the statement into two parts. The first part of the statement is: 3 DecimalFormatformatter= This declares a variable named formatter. The data type of the variable is DecimalFormat. Because the word DecimalFormat is not the name of a primitive data type, Java assumes it to be the name of a class. Recall from Chapter 2 that a variable of a class type is known as a reference variable, and it is used to hold the memory address of an object. When a reference variable holds an objects memory address, it is said that the variable references the object. So, the formatter variable will be used to reference a DecimalFormat object. The = operator that appears next assigns the address of an object that is created by the second part of the statement: newDecimalFormat(#0.00); This part of the statement uses the key word new, which creates an object in memory. After the word new, the name DecimalFormat appears, followed by some data enclosed in a set of parentheses. The name DecimalFormat specifies that an object of the DecimalFormat class should be created. Now lets look at the data appearing inside the parentheses. When an object is created, a special method known as a constructor is automatically executed. The purpose of the constructor is to initialize the objects attributes with appropriate data and perform any necessary setup operations. In other words, it constructs the object. The data that appears inside the parentheses is an argument that is passed to the constructor. When you create a DecimalFormat object, you pass a string that contains a formatting pattern to the constructor. A formatting pattern consists of special characters specifying how floating-point numbers should be formatted. In this example the string #0.00 is being passed to the constructor. This string will be assigned to one of the objects internal attributes. After the statement executes, the formatter variable will reference the object that was created in memory. This is illustrated in Figure 3-24. Figure 3-24 The formatter variable references a DecimalFormat object 172 Chapter 3 Decision Structures Each character in the formatting pattern corresponds with a position in a number. The first two characters, #0, correspond to the two digits before the decimal point, the period indicates the decimal point, and the characters 00 correspond to two digits after the decimal point. The # character specifies that a digit should be displayed in this position if it is present. If there is no digit in this position, no digit should be displayed. The 0 character also specifies that a digit should be displayed in this position if it is present. However, if there is no digit present in this position, a 0 should be displayed. The two zeros that appear after the decimal point indicate that numbers should be rounded to two decimal places. Once you have properly created a DecimalFormat object, you call its format method and pass the number you wish to format as an argument. The method returns a string containing the formatted number. For example, look at the program in Code Listing 3-14. Code Listing 3-14 (Format1.java) 1 import java.text.DecimalFormat; 2 3 /** 4 This program demonstrates the DecimalFormat class. 5 */ 6 7 public class Format1 8 { 9 public static void main(String[] args) 10 { 11 double number1 = 0.166666666666667; 12 double number2 = 1.666666666666667; 13 double number3 = 16.666666666666667; 14 double number4 = 166.666666666666667; 15 16//CreateaDecimalFormatobject. 17DecimalFormatformatter=newDecimalFormat(#0.00); 18 19//Displaytheformattedvariablecontents. 20System.out.println(formatter.format(number1)); 21System.out.println(formatter.format(number2)); 22System.out.println(formatter.format(number3)); 23System.out.println(formatter.format(number4)); 24} 25} Program Output 0.17 1.67 16.67 166.67 Creating Objects with the DecimalFormat Class 173 Notice the difference between the # character and the 0 character in the formatting pattern. The # symbol causes no digits to be displayed, while the 0 character causes leading zeros to be displayed. For example, look at the program in Code Listing 3-15. This is the same program as shown in Code Listing 3-14, but using a different format pattern. Code Listing 3-15 (Format2.java) 1 import java.text.DecimalFormat; 2 3 /** 4 This program demonstrates the DecimalFormat class. 5 */ 6 7 public class Format2 8 { 9 public static void main(String[] args) 10 { 11 double number1 = 0.166666666666667; 12 double number2 = 1.666666666666667; 13 double number3 = 16.666666666666667; 14 double number4 = 166.666666666666667; 15 16//CreateaDecimalFormatobject. 17DecimalFormatformatter=newDecimalFormat(000.00); 18 19//Displaytheformattedvariablecontents. 20System.out.println(formatter.format(number1)); 21System.out.println(formatter.format(number2)); 22System.out.println(formatter.format(number3)); 23System.out.println(formatter.format(number4)); 24} 25} 3 Program Output 000.17 001.67 016.67 166.67 You can also insert a comma into the format pattern to create grouping separators in formatted numbers. The program in Code Listing 3-16 demonstrates. 174 Chapter 3 Decision Structures Code Listing 3-16 (Format3.java) 1 import java.text.DecimalFormat; 2 3 /** 4 This program demonstrates the DecimalFormat class. 5 */ 6 7 public class Format3 8 { 9 public static void main(String[] args) 10 { 11 double number1 = 123.899; 12 double number2 = 1233.899; 13 double number3 = 12345.899; 14 double number4 = 123456.899; 15 double number5 = 1234567.899; 16 17//CreateaDecimalFormatobject. 18DecimalFormatformatter=newDecimalFormat(#,##0.00); 19 20//Displaytheformattedvariablecontents. 21System.out.println(formatter.format(number1)); 22System.out.println(formatter.format(number2)); 23System.out.println(formatter.format(number3)); 24System.out.println(formatter.format(number4)); 25System.out.println(formatter.format(number5)); 26} 27} Program Output 123.90 1,233.90 12,345.90 123,456.90 1,234,567.90 You can also format numbers as percentages by writing the % character at the last position in the format pattern. This causes a number to be multiplied by 100, and the % character is appended to its end. The program in Code Listing 3-17 demonstrates. Creating Objects with the DecimalFormat Class 175 Code Listing 3-17 (Format4.java) 1 import java.text.DecimalFormat; 2 3 /** 4 This program demonstrates the DecimalFormat class. 5 */ 6 7 public class Format4 8 { 9 public static void main(String[] args) 10 { 11 double number1 = 0.12; 12 double number2 = 0.05; 13 14//CreateaDecimalFormatobject. 15DecimalFormatformatter=newDecimalFormat(#0%); 16 17//Displaytheformattedvariablecontents. 18System.out.println(formatter.format(number1)); 19System.out.println(formatter.format(number2)); 20} 21} 3 Program Output 12% 5% Checkpoint 3.29 What is the purpose of the new keyword? 3.30 What is a constructor? 3.31 Assume that the double variable number holds the value 459.6329. What format pattern would you use to display the number as 00459.633? 3.32 Assume that the double variable number holds the value 0.179. What format pattern would you use to display the number as .18? 3.33 Assume that the double variable number holds the value 7634869.1. What format pattern would you use to display the number as 7,634,869.10? 176 Chapter 3 Decision Structures Case Study on CD-ROM: Calculating Sales Commission The Student CD contains a valuable case study demonstrating how sales commissions may be calculated using various commission rates. The commission rate is determined by the amount of sales. 3.11 The printf Method (Optional) In Java 5 you can perform formatted console output with the System.out.printf method. The methods general format is: System.out.printf(FormatString, ArgumentList) CONCEPT THE System.out.printf METHOD ALLOWS YOU TO FORMAT OUTPUT IN A VARIETY OF WAYS. In the general format, FormatString is a string that contains text and/or special formatting specifiers. ArgumentList is a list of zero or more additional arguments, which will be formatted according to the format specifiers listed in the format string. The simplest way you can use the printf method is with only a format string, and no additional arguments. Here is an example: System.out.printf(I love Java programming.\n); The format string in this example is I love Java programming.\n. It does not contain any format specifiers, so this method call simply prints the string I love Java programming.\n. Using the method in this fashion is like using the System.out.print method. Now lets look at an example that uses a format specifier and an additional argument: int hours = 40; System.out.printf(I worked %d hours this week.\n, hours); In this example, the %d is a format specifier for a decimal integer. When this string is printed, the %d will not be displayed. Instead, the value of the hours argument will be printed in place of the format specifier. Here is the output of the code: I worked 40 hours this week. In this example, the %d format specifier was used because the hours variable is an int. An error will occur if you use %d with a non-integer value. Heres another example: int dogs = 2; int cats = 4; System.out.printf(We have %d dogs and %d cats.\n, dogs, cats); The printf Method 177 First, notice that this example uses two %d format specifiers in the format string. Also notice that two arguments appear after the format string. The value of the first integer argument, dogs, will be printed in place of the first %d, and the value of the second integer argument, cats, will be printed in place of the second %d. The code will produce the following output: We have 2 dogs and 4 cats. These examples show the one-to-one correspondence between the format specifiers and the arguments that appear after the format string. The following code shows another example: int value1 = 3; int value2 = 6; int value3 = 9; System.out.printf(%d %d %d\n, value1, value2, value3); 3 In the printf method call, there are three format specifiers and three additional arguments after the format string. This code will produce the following output: 3 6 9 Now lets actually apply some formatting to the values we are displaying. A format specifier may also include a field width. Here is an example: int number = 9; System.out.printf(The value is %6d\n, number); The format specifier %6d indicates that the argument number should be printed in a field that is 6 places wide. If the value in number is shorter than 6 places, it will be right justified. Here is the output of the code. The value is 9 If the value of the argument is wider than the specified field width, the field width will be expanded to accommodate the value. For example, look at the following code: int number = 97654; System.out.printf(The value is %2d\n, number); In this code the field width is two spaces, but the value being displayed, 97654, requires five spaces. Because the field width will be automatically expanded to accommodate the number, this code will produce the following output: The value is 97654 178 Chapter 3 Decision Structures Field widths can help when you need to print values aligned in columns. For example, look at the following code. int num1 = 97654, num2 int num3 = 86, num4 int num5 = 246, num6 Sy...

Textbooks related to the document above:

Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Indiana State - CS - 320
Chapter2Java Fundamentals2.1 The Parts of a Java Programava programs are made up of different parts. Your first step in learning Java is to learn what the parts are. We will begin by looking at a simple example, shown in Code Listing 2-1.Chap
Indiana State - CS - 320
Starting Out With Java 5(Control Structures to Objects)Chapter 13By Tony GaddisCopyright 2005 Pearson Addison-Wesley. All rights reserved.Chapter TopicsChapter 13 discusses the following main topics: The Swing and AWT Class Hierarchy
Indiana State - CS - 320
Starting Out With Java 5(Control Structures to Objects)Chapter 11By Tony GaddisCopyright 2005 Pearson Addison-Wesley. All rights reserved.Chapter TopicsChapter 11 discusses the following main topics: What Is Inheritance? Calling th
Indiana State - CS - 320
Starting Out With Java 5(Control Structures to Objects )Chapter 2By Tony GaddisCopyright 2005 Pearson Addison-Wesley. All rights reserved.Introduction To Computers And JavaChapter Objectives To understand: the meaning and placement of the
Indiana State - CS - 320
Starting Out With Java 5(Control Structures to Objects)Chapter 3By Tony GaddisCopyright 2005 Pearson Addison-Wesley. All rights reserved.Decision StructuresChapter ObjectivesTo understand: how to write boolean expressions how to write:
Indiana State - CS - 320
Starting Out With Java 5(Control Structures to Objects )Chapter 1By Tony GaddisCopyright 2005 Pearson Addison-Wesley. All rights reserved.Introduction To Computers And JavaChapter Objectives To understand: the necessity of programm
Indiana State - CS - 320
Starting Out With Java 5(Control Structures to Objects)Chapter 15By Tony GaddisCopyright 2005 Pearson Addison-Wesley. All rights reserved.Chapter TopicsChapter 15 discusses the following main topics: Introduction to Recursion Solving P
Indiana State - CS - 320
Starting Out With Java 5(Control Structures to Objects)Chapter 14By Tony GaddisCopyright 2005 Pearson Addison-Wesley. All rights reserved.Chapter TopicsChapter 14 discusses the following main topics: Introduction to Applets A Brief Introd
Indiana State - SESSION - 2
2004 Indiana Student Achievement InstituteGUIDANCE FORCE FIELD INQUIRY QUESTIONSGUIDANCE CURRICULUM 1. What percentage of our counselors' time should be spent on each of the following activities:Guidance NDEFINITIOActivities that help all studen
Indiana State - SESSION - 2
2004 Indiana Student Achievement InstituteEXPECTATIONS FORCE FIELD INQUIRY QUESTIONS1. 2. 3. 4.Do our teachers have high expectations for students? What evidence backs up your opinion? Do our community members have high expectations for student
Indiana State - SESSION - 2
LIVING BY OUR VISION STUDENT BEHAVIORS &amp; ATTITUDES As you look around your school, where do you see students showing each behavior and attitude?Behavior or Attitude Observation Students Showing This Behavior or Attitude Observation Students Not Sho
Indiana State - IRT - 2
TABLE 414-, 5-, 6- and 7-Year Graduation Rates of Entering Freshmen Fall 1990 through Fall 1996by Full-Time/Part-Time StatusNumber Graduated BEFORE Fall 5Number PercentFull-Time1990381 19% 688 34% 793 39% 841 42%Part-Time1994343 17% 655
Indiana State - IRT - 2
TABLE 424-, 5-, 6- and 7-Year Graduation Rates of Entering Freshmenby Pell Grant StatusNumber Graduated BEFORE Fall 5 Number Percent Fall 6 Number Percent Fall 7 Number Percent Fall 8 Number PercentReceived Pell Grant First Semester1991 89 13%
Indiana State - IRT - 2
TABLE 425-, 6-, 7- and 8-Year Graduation Rates of Entering Freshmen Fall 1989 through Fall 1994by Pell Grant StatusReceived Pell Grant First Semester1989 Graduated Fall 5 Number Percent Graduated Fall 6 Number Percent Graduated Fall 7 Number Per
Indiana State - IRT - 2
TABLE 415-, 6-, 7- and 8-Year Graduation Rates of Entering Freshmen Fall 1989 through Fall 1994by Full-Time/Part-Time StatusFull-Time1989 Graduated Fall 5 Number Percent Graduated Fall 6 Number Percent Graduated Fall 7 Number Percent Graduated F
Indiana State - IRT - 2
TABLE 434-, 5-, 6- and 7-Year Graduation Rates of Entering Freshmen by High School GPA Fall 1990 through Fall 1996Number Graduated BEFORE Fall 5Number Percent1.00 - 2.24199032 7% 94 21% 117 26% 126 29%2.25 - 2.491994 199523 6% 57 15% 72 2
Indiana State - IRT - 2
TABLE 36 Retention Rates of Entering Freshmenby Pell Grant StatusNumber Enrolled BEFORE Fall 1 Number Percent Fall 2 Number Percent Fall 3 Number Percent Fall 4 Number Percent Fall 5 Number Percent Fall 6 Number PercentPell Grant Recipient First
Indiana State - IRT - 2
TABLE 394-, 5-, 6- and 7-Year Graduation Rates of Entering Freshmen by EthnicityNumber Graduated BEFORE Fall 5Number PercentAfrican-American19916 4% 19 12% 24 15% 30 18%American Indian199521 10% 39 19% 19 9%Caucasian19950 0% 0 0% 0 0%
Indiana State - IRT - 2
TABLE 384-, 5-, 6- and 7-Year Graduation Rates of Entering Freshmen by School/CollegeNumber Graduated BEFORE Fall 5Number PercentArts and Sciences1991113 23% 188 38% 207 42% 217 44%Business1995128 21% 205 34% 154 23%Education1994 1995
Indiana State - IRT - 2
TABLE 384-, 5-, 6- and 7-Year Graduation Rates of Entering Freshmen Fall 1990 through Fall 1996 by School/CollegeNumber Graduated BEFORE Fall 5Number PercentArts and Sciences1990118 21% 188 34% 216 39% 228 41%Business1995127 21% 204 33% 23
Indiana State - IRT - 2
TABLE 394-, 5-, 6- and 7-Year Graduation Rates of Entering Freshmen Fall 1990 through Fall 1996 by EthnicityNumber Graduated BEFORE Fall 5Number Percent199015 8% 39 20% 48 25% 51 27%19916 4% 19 12% 24 15% 30 18%1992African-American 1993
Indiana State - IRT - 2
TABLE 404-, 5-, 6- and 7-Year Graduation Rates of Entering Freshmenby SAT Verbal ScoresNumber Graduated BEFORE Fall 5 Number Percent Fall 6 Number Percent Fall 7 Number Percent Fall 8 Number PercentScore of 200 - 4191992 55 11% 132 26% 153 31%
Indiana State - IRT - 2
TABLE 36 Retention Rates of Entering Freshmen Fall 1989 through Fall 1998by Pell Grant StatusPell Grant Recipient First Semester1989 Enrolled Fall 1 Number Percent Enrolled Fall 2 Number Percent Enrolled Fall 3 Number Percent Enrolled Fall 4 Numb
Indiana State - IRT - 2
TABLE 395-, 6-, 7- and 8-Year Graduation Rates of Entering Freshmen by EthnicityAfrican-American1990 Graduated Fall 5 Number Percent Graduated Fall 6 Number Percent Graduated Fall 7 Number Percent Graduated Fall 8 Number Percent 15 8% 39 20% 48 2
Indiana State - IRT - 2
TABLE 435-, 6-, 7- and 8-Year Graduation Rates of Entering Freshmen by High School GPA Fall 1989 through Fall 19941.00 - 2.241989 Graduated Fall 5 Number Percent Graduated Fall 6 Number Percent Graduated Fall 7 Number Percent Graduated Fall 8 Num
Indiana State - IRT - 2
TABLE 37Retention Rates of Entering Freshmen by High School GPANumber Enrolled BEFORE Fall 1 Number Percent Fall 2 Number Percent Fall 3 Number Percent Fall 4 Number Percent Fall 5 Number Percent Fall 6 Number Percent1.00 - 2.241992 1993 1994 1
Indiana State - IRT - 2
TABLE 414-, 5-, 6- and 7-Year Graduation Rates of Entering Freshmenby Full-Time/Part-Time StatusNumber Graduated BEFORE Fall 5 Number Percent Fall 6 Number Percent Fall 7Number PercentFull-Time1992 407 19% 783 35%853 39%Part-Time1996 415
Indiana State - IRT - 2
TABLE 36 Retention Rates of Entering Freshmenby Pell Grant StatusNumber Enrolled BEFORE Fall 1Number PercentPell Grant Recipient First Semester1993678 100% 442 65% 340 50% 274 40% 184 27% 62 9%Did Not Receive Pell Grant First Semester20016
Indiana State - IRT - 2
TABLE 37Retention Rates of Entering Freshmen by High School GPA Fall 1989 through Fall 19981.00 - 2.241989 Enrolled Fall 1 Number Percent Enrolled Fall 2 Number Percent Enrolled Fall 3 Number Percent Enrolled Fall 4 Number Percent Enrolled Fall 5
Indiana State - IRT - 2
TABLE 37Retention Rates of Entering Freshmen by High School GPANumber Enrolled BEFORE Fall 1Number Percent1.00 - 2.241993411 100% 221 54% 161 39% 125 30% 102 25% 39 9%2.25 - 2.491999287 100% 187 65% 133 46% 113 39%2.50 - 2.741999289 1
Indiana State - IRT - 2
TABLE 37Retention Rates of Entering Freshmen by High School GPA Fall 1990 through Fall 1999Number Enrolled BEFORE Fall 1Number Percent1.00 - 2.241990442 100% 260 59% 193 44% 179 40% 121 27% 47 11%2.25 - 2.491996252 100% 137 54% 110 44% 10
Indiana State - WINDOWS - 95
Application Name: WebStressVersion: 2.0Release Date: 25 - 8 - 99Platform: Windows 95 and NT32 Bit FileSize: 359000 bytes16 Bit FileSize: bytesPrice: $30Registration Status: SharewareEval Period: Application Home Page: http:/www.paessler.co
Indiana State - WINDOWS - 95
Application Name: Dial-up Networking Connection SharerVersion: 2.1Release Date: 08 - 12 - 98Platform: Windows 9532 Bit FileSize: 181574 bytes16 Bit FileSize: bytesPrice: $20.00Registration Status: SharewareEval Period: You can create 10 dis
Indiana State - IRT - 2
Spring 2003 Sections Taught by Faculty Type University Summary Standard Sections Arranged Sections Distance Sections Total Reg LLL # Faculty Number Pct Number Pct Number Pct Sections Sections 151 352 20% 199 30% 47 25% 598 5 125 346 20% 158 24% 43 23
Indiana State - IRT - 2
Fall 2002 Sections Taught by Faculty Type University Summary Standard Sections Arranged Sections Distance Sections Total Reg LLL # Faculty Number Pct Number Pct Number Pct Sections Sections 167 385 20% 203 34% 71 37% 659 11 130 402 21% 153 25% 42 22%
Indiana State - IRT - 2
Spring 2003 Sections Taught by Faculty Type Departmental Summaries Standard Sections Arranged Sections Number Pct Number Pct Distance Sections Total Reg LLL Number Pct Sections SectionsFaculty Type ARTS &amp; SCIENCES African &amp; African-Amer Studies PRO
Indiana State - IRT - 2
FTE Distribution by Faculty Type Fall 2002 Departmental Summaries Number of Faculty Dir Inst FTE Inst Supp Research FTE FTE Admin FTE Service FTE Total FTE Pct Dir Inst Pct Pct Inst Supp Research Pct Admin Pct ServiceCategory ARTS &amp; SCIENCES Africa
Indiana State - IRT - 2
Spring 2003 Average Section Size by Faculty Type by Section TypeFaculty Type PROFESSOR-FULL PROFESSOR-ASSOCIATE PROFESSOR-ASSISTANT OTHER FULL-TIME REG FULL-TIME TEMPORARY PART-TIME GRADUATE ASSISTANT ADMINISTRATIVE/OTHER University Total# Facult
Indiana State - IRT - 2
Spring 2003 Average Section Size by Level by Faculty Type Standard Sections Only Departmental Summaries Number of Sections Multi Multi UG UG/GR Grad Average Section Size Multi Multi UG UG/GR GradFaculty Type ARTS &amp; SCIENCES African &amp; African-Amer S
Indiana State - IRT - 2
Fall 2002 Average Section Size by Faculty Type by Section Type Departmental Summaries Ave # Std % of Secs Sections Taught by Number of Sections Taught Number of Students Enrolled Average Section Size Lifelong Learning # Faculty Taught Standard Arrang
Indiana State - IRT - 2
Fall 2002 Average Section Size by Level by Faculty Type Standard Sections Only Departmental Summaries Number of Sections Multi Multi UG UG/GR Grad Average Section Size Upper Multi Multi Div UG UG/GR GradFaculty Type ARTS &amp; SCIENCES African &amp; Africa
Indiana State - IRT - 2
Spring 2003 Average Section Size by Level by Faculty Type Standard, Arranged and Distance Sections Departmental Summaries Number of Sections Multi Multi UG UG/GR Grad Average Section Size Multi Multi UG UG/GR GradFaculty Type ARTS &amp; SCIENCES Africa
Indiana State - IRT - 2
Spring 2003 Average Section Size by Level by Faculty Type Standard, Arranged and Distance Sections Number of Sections Lower Upper Multi Multi Div Div UG UG/GR Grad 119 225 24 44 186 176 203 18 26 124 203 284 22 32 123 4 0 0 0 0 176 106 9 9 25 143 87
Indiana State - IRT - 2
Characteristics of High School Students Entering Different Types of Postsecondary Institutions in the United StatesOffice of Strategic Planning, Institutional Research &amp; Effectiveness INTRODUCTION When the public is anxious about the direction of ou
Indiana State - IRT - 2
Indiana State University2007 Freshman Student Profile: NSSE EditionThe National Survey of Student Engagement (NSSE) was administered to randomly selected ISU freshman students in Spring 2007. Out of 2,210 freshman students given the opportunity to
Indiana State - IRT - 2
Indiana State University Official Summary of Retention/Graduation Rates and Migration Of Entering Freshmen Cohorts by Department Structure of the Report and Definition of Terms The Official Summary of Retention/Graduation Rates and Migration traces f
Indiana State - IRT - 2
How Do NSSE Benchmarks Illustrate ISU Second Year Returning Student?Office of Strategic Planning, Institutional Research &amp; EffectivenessINTRODUCTION In the spring of 2003, Indiana State University (ISU) participated in the National Survey of Stude
Indiana State - IRT - 2
College of TechnologyThe Freshman Profile, Fall 2007In2007,OSPIREmademajorrevisionstotheStudentInformationQuestionnaire(SIQ).Sincethen,wehavebeenadjustingthesurveytoaccommodatethe informationalneedsoftheISUcommunity,whilealsomaintainingcontinuitywi
Indiana State - IRT - 2
College of NursingThe Freshman Profile, Fall 2005NOTE: DUE TO SMALL SAMPLE SIZES, SOME STATISTICS MAY NOT BE APPROPRIATE FOR ANALYTICAL PURPOSES.The survey instrument administered to Fall 2005 Freshman Sycamore Advantage participants was the same
Indiana State - IRT - 2
College of Health &amp; Human PerformanceThe Freshman Profile, Fall 2004NOTE: DUE TO SMALL SAMPLE SIZES, SOME STATISTICS MAY NOT BE APPROPRIATE FOR ANALYTICAL PURPOSES.The survey instrument administered to Fall 2004 Freshman Sycamore Advantage partici
Indiana State - IRT - 2
School of Business The Freshman Profile, Fall 1998The survey instrument administered to Fall 1998 Freshman NSARP participants was the same one administered to the previous Freshman class. A separate report provides a profile of the entire Fall 1998
Indiana State - IRT - 2
College of NursingThe Freshman Profile, Fall 2004NOTE: DUE TO SMALL SAMPLE SIZES, SOME STATISTICS MAY NOT BE APPROPRIATE FOR ANALYTICAL PURPOSES.The survey instrument administered to Fall 2004 Freshman Sycamore Advantage participants was the same
Indiana State - IRT - 2
Indiana State UniversityThe Freshman Profile, Fall 2005In 1997, OSPIRE made major revisions to the Student Information Questionnaire (SIQ). Since then, we have been adjusting the survey to accommodate the informational needs of the ISU community, w
Indiana State - IRT - 2
College of Health &amp; Human PerformanceThe Freshman Profile, Fall 2007In 2007, OSPIRE made major revisions to the Student Information Questionnaire (SIQ). Since then, we have been adjusting the survey to accommodate the informational needs of the I
Indiana State - IRT - 2
College of EducationThe Freshman Profile, Fall 2006NOTE: DUE TO SMALL SAMPLE SIZES, SOME STATISTICS MAY NOT BE APPROPRIATE FOR ANALYTICAL PURPOSES.The survey instrument administered to Fall 2006 Freshman Sycamore Advantage participants was the sam
Indiana State - IRT - 2
College of TechnologyThe Freshman Profile, Fall 2005NOTE: DUE TO SMALL SAMPLE SIZES, SOME STATISTICS MAY NOT BE APPROPRIATE FOR ANALYTICAL PURPOSES.The survey instrument administered to Fall 2005 Freshman Sycamore Advantage participants was the sa
Indiana State - IRT - 2
College of Arts &amp; SciencesThe Freshman Profile, Fall 2006NOTE: DUE TO SMALL SAMPLE SIZES, SOME STATISTICS MAY NOT BE APPROPRIATE FOR ANALYTICAL PURPOSES.The survey instrument administered to Fall 2006 Freshman Sycamore Advantage participants was t
Indiana State - IRT - 2
College of BusinessThe Freshman Profile, Fall 2006NOTE: DUE TO SMALL SAMPLE SIZES, SOME STATISTICS MAY NOT BE APPROPRIATE FOR ANALYTICAL PURPOSES.The survey instrument administered to Fall 2006 Freshman Sycamore Advantage participants was the same
Indiana State - IRT - 2
Indiana State UniversityThe Freshman Profile, Fall 2006In 2000, OSPIRE made major revisions to the Student Information Questionnaire (SIQ). Since then, we have been adjusting the survey to accommodate the informational needs of the ISU community, w
Indiana State - IRT - 2
School of Technology The Freshman Profile, Fall 1998The survey instrument administered to Fall 1998 Freshman NSARP participants was the same one administered to the previous Freshman class. A separate report provides a profile of the entire Fall 199
Indiana State - IRT - 2
College of Arts &amp; SciencesThe Freshman Profile, Fall 2004NOTE: DUE TO SMALL SAMPLE SIZES, SOME STATISTICS MAY NOT BE APPROPRIATE FOR ANALYTICAL PURPOSES.The survey instrument administered to Fall 2004 Freshman Sycamore Advantage participants was t