Computer Science Notes Chapter 3 Page 1 of 19 Chapter 3: Selection Statements These notes are meant to accompany Introduction to Java Programming: Fundamentals First, sixth edition by Y. Daniel Lang. Programming Skills in a Nutshell: At the end of this chapter you should have the following programming skills: 1. Translate logical conditions into Boolean expressions. 2. To use simple if … else statements to control program flow. 3. To use nested if statements for multiple outcomes and conditions. 4. To use a switch statement for multiple outcomes and conditions that are based on a positive integer. 5. Here is a template that uses the key programming skills you should have at this point: import java.util.Scanner; // The import statement tells the compiler where to find the Scanner class, // which is used for user input. /**The Chap03Basics class implements an application that * performs various mathematical tasks, and is meant to * illustrate the basics of selection statements * (i.e., if and switch statements). * This is meant as an example of the material in Chapter 3 of the text * _Introduction to Java Programming: Fundamentals First_ by Y. D. Liang * @author Kevin Mirus */ public class Chap03Basics { /** Gives the user a menu of options of mathematical calculations. * @param args is not used. */ public static void main(String[] args) { //Tell the user what the program does String programPurpose = "This program performs various mathematical calculations."; System.out.println(programPurpose); System.out.println("\nYour menu of choices is:"); System.out.println("t: Get quiz questions from the Math Tutor."); System.out.println("f: Get some Math Facts about a number you enter."); System.out.println("g: Convert a number score into a com sci letter Grade."); System.out.println("c: Compute the tax on a purchase."); System.out.println("Enter a single letter for your menu choice"); //Declare a vhar variable for the user's menu choice. char menuChoice; String menuChoiceString; //Create a Scanner object for reading in the user's input Scanner keyboard = new Scanner(System.in); //get the user's data menuChoiceString = keyboard.next(); menuChoice = menuChoiceString.charAt(0); Computer Science Notes Chapter 3 Page 2 of 19 //perform appropriate menu item action switch (menuChoice) { case 't': //Generate quiz questions from the Math Tutor //First, do an addition quiz problem //use the fact that the Math.random() method //generates random floating point numbers between 0 and 1 System.out.println("\nHere come four arithmetic questions:"); int number1 = (int) (Math.random() * 10); int number2 = (int) (Math.random() * 10); int correctAnswer = number1 + number2; int userAnswer; System.out.println("What is " + number1 + " + " + number2 + " ?"); userAnswer = keyboard.nextInt(); if (userAnswer == correctAnswer) System.out.println("You are correct!"); else System.out.println("Sorry, the correct answer is: " + correctAnswer); //Second, do a subtraction quiz problem number1 = (int) (Math.random() * 10); number2 = (int) (Math.random() * 10); //Swap numbers if necessary so number1 is greater than number 2 if (number2 > number1) { int temp = number1; number1 = number2; number2 = temp; } correctAnswer = number1 - number2; System.out.println("\nWhat is " + number1 + " - " + number2 + " ?"); userAnswer = keyboard.nextInt(); if (userAnswer == correctAnswer) System.out.println("You are correct!"); else System.out.println("Sorry, the correct answer is: " + correctAnswer); //Third, do a multiplication quiz problem number1 = (int) (Math.random() * 10); number2 = (int) (Math.random() * 10); correctAnswer = number1 * number2; System.out.println("\nWhat is " + number1 + " * " + number2 + " ?"); userAnswer = keyboard.nextInt(); if (userAnswer == correctAnswer) System.out.println("You are correct!"); else System.out.println("Sorry, the correct answer is: " + correctAnswer); //Fourth, do a division quiz problem number1 = (int) (Math.random() * 10); number2 = (int) (Math.random() * 10) * number1; correctAnswer = number2 / number1; System.out.println("\nWhat is " + number2 + " / " + number1 + " ?"); userAnswer = keyboard.nextInt(); if (userAnswer == correctAnswer) System.out.println("You are correct!"); else System.out.println("Sorry, the correct answer is: " + correctAnswer); break; Computer Science Notes Chapter 3 Page 3 of 19 case 'f': //Generate some Math Facts about a number the user enters //Get user's number System.out.println("\nEnter an integer, please."); number1 = keyboard.nextInt(); //Determine if number is even or odd boolean isEven = (number1 % 2) == 0; if (isEven) System.out.println(number1 + " is even."); else System.out.println(number1 + " is odd."); //Print the absolute value of the number System.out.println("Here is the absolute value of your number:"); if (number1 < 0) System.out.println("|" + number1 + "| = " + (-number1)); else System.out.println("|" + number1 + "| = " + number1); //Print the absolute value of the number System.out.println("Here are some factors of your number:"); if (number1%2 == 0) System.out.println(number1 + " is divisible by 2."); if (number1%3 == 0) System.out.println(number1 + " is divisible by 3."); if (number1%5 == 0) System.out.println(number1 + " is divisible by 5."); if (number1%7 == 0) System.out.println(number1 + " is divisible by 7."); if (number1%11 == 0) System.out.println(number1 + " is divisible by 11."); if (Math.abs(number1) > 121) System.out.println(number1 + " may have prime factors larger than 11, " + "but this program can not determine them."); break; case 'g': //Convert a number score into a com sci letter Grade System.out.println("\nEnter your computer science number grade."); double score = keyboard.nextDouble(); String letterGrade; //A //AB //B //BC //C //D //F 92 % - 100 % 88 % - 91 % 82 % - 87 % 78 % - 81 % 72 % - 77 % 65 % - 71 % 0 % - 64 % if (score >= 91.5) letterGrade = "A"; else if (score >= 87.5) letterGrade = "AB"; else if (score >= 81.5) letterGrade = "B"; else if (score >= 77.5) letterGrade = "BC"; else if (score >= 71.5) Computer Science Notes Chapter 3 Page 4 of 19 letterGrade = "C"; else if (score >= 64.5) letterGrade = "D"; else letterGrade = "F"; System.out.println("A score of " + score + " earns a letter grade of " + letterGrade); break; case 'c': //Compute the tax on a purchase System.out.println("\nPlease enter the purchase price:"); double price = keyboard.nextDouble(); System.out.println("Please enter the tax rate as a decimal:"); double taxRate = keyboard.nextDouble(); double totalPrice = price * (1 + taxRate); System.out.println("The total price as an unformatted number is: $" + totalPrice); System.out.printf("The total price as an formatted number is: $%4.2f\n", totalPrice); break; default: System.out.println("That was not a valid menu choice."); } System.out.println("\n\nHere are some miscellaneous applications from Chapter 3:"); boolean lovePackers = true; boolean loveWisconsin = true; System.out.println("Type true if you love the Packers, "); System.out.println("or type false if you dislike the Packers."); lovePackers = keyboard.nextBoolean(); System.out.println("Type true if you love Wisconsin, "); System.out.println("or type false if you dislike Wisconsin."); loveWisconsin = keyboard.nextBoolean(); if (loveWisconsin == true && lovePackers == true) System.out.println("You must be a native Wisconsinite."); else if (loveWisconsin == true && lovePackers == false) System.out.println("You must be a Wisconsin immigrant."); else if (loveWisconsin == false && lovePackers == true) System.out.println("You must be from Minnesota."); else if (loveWisconsin == false && lovePackers == false) System.out.println("You must be from Illinois."); //Exclusive or: if (loveWisconsin ^ lovePackers) System.out.println("That's good enough for me."); //Longhand exclusive or: if ((loveWisconsin || lovePackers) && !(loveWisconsin && lovePackers)) System.out.println("That's good enough for me."); System.out.println("\n\nHere are some more examples of the printf() method:"); //The following line produces an output where the format specifier %6.2f //will be replaced with the //floating point number 1.5 written //using 6 spaces and 2 digits after the decimal point //(and followed by a newline). System.out.print("Price is: $%6.2f"); System.out.printf("Price is: $%6.2f\n", 1.5); Computer Science Notes Chapter 3 System.out.print("%5d"); System.out.printf("%5d\n", 123); System.out.print("%5x"); System.out.printf("%5x\n", 123); System.out.print("%5o"); System.out.printf("%5o\n", 123); System.out.print("%6.2f"); System.out.printf("%6.2f\n", 123.); System.out.print("%10.2e"); System.out.printf("%10.2e\n", 123.); System.out.print("%6.2g"); System.out.printf("%6.2g\n", 123.); System.out.print("%6s"); System.out.printf("%6s\n", "123"); System.out.print("%-5dhello"); System.out.printf("%-5dhello\n", 123); System.out.print("%06d"); System.out.printf("%06d\n", 123); System.out.print("%+6d"); System.out.printf("%+6d\n", 123); System.out.print("%(6d"); System.out.printf("%(6d\n", -123); System.out.print("%10d"); System.out.printf("%10d\n", 123000); //Tell the user that the program is done. System.out.println("\nProgram Chap03Basics has terminated."); }//end of main() }//end of class Chap03Basics Page 5 of 19 Computer Science Notes Chapter 3 /* ******************************************************************* * PROGRAM OUTPUT * ******************************************************************* This program performs various mathematical calculations. Your menu of choices is: t: Get quiz questions from the Math Tutor. f: Get some Math Facts about a number you enter. g: Convert a number score into a com sci letter Grade. c: Compute the tax on a purchase. Enter a single letter for your menu choice t Here come four arithmetic questions: What is 0 + 0 ? 5 Sorry, the correct answer is: 0 What is 5 - 2 ? 3 You are correct! What is 5 * 8 ? 41 Sorry, the correct answer is: 40 What is 36 / 9 ? 4 You are correct! Here are some miscellaneous applications from Chapter 3: Type true if you love the Packers, or type false if you dislike the Packers. true Type true if you love Wisconsin, or type false if you dislike Wisconsin. true You must be a native Wisconsinite. Here are some more examples of the printf() method: Price is: $%6.2fPrice is: $ 1.50 %5d 123 %5x 7b %5o 173 %6.2f123.00 %10.2e 1.23e+02 %6.2g1.2e+02 %6s 123 %-5dhello123 hello %06d000123 %+6d +123 %(6d (123) %10d 123000 Program Chap03Basics has terminated. Page 6 of 19 Computer Science Notes Chapter 3 Page 7 of 19 /* ******************************************************************* * PROGRAM OUTPUT * ******************************************************************* This program performs various mathematical calculations. Your menu of choices is: t: Get quiz questions from the Math Tutor. f: Get some Math Facts about a number you enter. g: Convert a number score into a com sci letter Grade. c: Compute the tax on a purchase. Enter a single letter for your menu choice f Enter an integer, please. -360 -360 is even. Here is the absolute value of your number: |-360| = 360 Here are some factors of your number: -360 is divisible by 2. -360 is divisible by 3. -360 is divisible by 5. -360 may have prime factors larger than 11, but this program can not determine them. Here are some miscellaneous applications from Chapter 3: Type true if you love the Packers, or type false if you dislike the Packers. true Type true if you love Wisconsin, or type false if you dislike Wisconsin. false You must be from Minnesota. That's good enough for me. That's good enough for me. … * ******************************************************************** */ Computer Science Notes Chapter 3 /* ******************************************************************* * PROGRAM OUTPUT * ******************************************************************* This program performs various mathematical calculations. Your menu of choices is: t: Get quiz questions from the Math Tutor. f: Get some Math Facts about a number you enter. g: Convert a number score into a com sci letter Grade. c: Compute the tax on a purchase. Enter a single letter for your menu choice g Enter your computer science number grade. 78 A score of 78.0 earns a letter grade of BC Here are some miscellaneous applications from Chapter 3: Type true if you love the Packers, or type false if you dislike the Packers. false Type true if you love Wisconsin, or type false if you dislike Wisconsin. true You must be a Wisconsin immigrant. That's good enough for me. That's good enough for me. … * ******************************************************************** */ Page 8 of 19 Computer Science Notes Chapter 3 /* ******************************************************************* * PROGRAM OUTPUT * ******************************************************************* This program performs various mathematical calculations. Your menu of choices is: t: Get quiz questions from the Math Tutor. f: Get some Math Facts about a number you enter. g: Convert a number score into a com sci letter Grade. c: Compute the tax on a purchase. Enter a single letter for your menu choice c Please enter the purchase price: 157.84 Please enter the tax rate as a decimal: .055 The total price as an unformatted number is: $166.5212 The total price as an formatted number is: $166.52 Here are some miscellaneous applications from Chapter 3: Type true if you love the Packers, or type false if you dislike the Packers. false Type true if you love Wisconsin, or type false if you dislike Wisconsin. false You must be from Illinois. … * ******************************************************************** */ Page 9 of 19 Computer Science Notes Chapter 3 Page 10 of 19 /* ******************************************************************* * PROGRAM OUTPUT * ******************************************************************* This program performs various mathematical calculations. Your menu of choices is: t: Get quiz questions from the Math Tutor. f: Get some Math Facts about a number you enter. g: Convert a number score into a com sci letter Grade. c: Compute the tax on a purchase. Enter a single letter for your menu choice q That was not a valid menu choice. … * ******************************************************************** */ Book’s Statement of Skills: 1. To declare boolean type variables and write Boolean expressions. (3.2) 2. To distinguish between conditional and unconditional && and || operators. (3.2.1) 3. To use Boolean expressions to control selection statements. (3.3 – 3.5) 4. To implement selection control using if and nested if statements. (3.3) 5. To implement selection control using switch statements. (3.4) 6. To write expressions using the conditional operator. (3.5) 7. To display formatted output using the System.out.printf method and to format strings using the String.format method. (3.6) 8. To know the rules governing operand evaluation order, operator precedence, and operator associativity. (3.7 – 3.8) Computer Science Notes Chapter 3 Page 11 of 19 Section 3.1: Introduction This chapter will teach you how to if and switch statements, which are used to which lines of code a program executes based on user input or the values stored in variables. Example: Problem to solve: If the user enters a negative value for a radius of a circle, then display an error message; otherwise compute and display the circumference. ↓ Pseudocode.. Get the user’s input for a circle radius If (the radius is negative) Then print an error message Otherwise Compute and print the circumference ↓ Real code // Get the user’s input for a circle radius System.out.println("Enter the radius of a circle:"); Scanner keyboard = new Scanner(System.in); double radius = keyboard.nextDouble(); if (radius < 0.0) System.out.println("Bad entry; you entered r = “ + radius + “, and the radius of a circle should not be negative"); else System.out.println("For a circle of radius “ + radius + “, the circumference is: " + (2*Math.PI*radius)); Section 3.2: boolean Data Type and Operations Comparison operators: <, <=, >, >=, ==, != The boolean data type contains one of two values: true or false. Boolean operators: !, &&, ||, ^ Section 3.2.1: Unconditional vs. Conditional Boolean Operators && is a conditional, or short-circuit operator because if the first expression evaluates to false, the second expression’s value is not computed. & is an unconditional operator because both expressions’ values are computed. Section 3.2.2: Example: Determining Leap Year Section 3.2.3: Example: A Simple Math Learning Tool (see sample code Chap03Basics at start of lecture notes…) Computer Science Notes Chapter 3 Page 12 of 19 Section 3.3: if Statements An if statement is used to force a program to execute certain lines of code based on the truth of a given condition. Section 3.3.1: Simple if Statements The if statement by itself forces a program to execute a statement only if a given condition is true. Syntax of a simple if statement: if (condition) { conditionTrueStatement(s); } nextStatement; When the condition is false, the program executes nextStatement right away, thus skipping conditionTrueStatement(s), but when the condition is true, the program executes conditionTrueStatement(s) first, and then nextStatement. Example: // Get the user’s input for a circle radius System.out.println("Enter the radius of a circle:"); Scanner keyboard = new Scanner(System.in); double radius keyboard.nextDouble(); double circumference; if (radius >= 0.0) { circumference = 2*Math.PI*radius; System.out.println("For a circle of radius “ + radius + “, the circumference is: " + circumference); } Computer Science Notes Chapter 3 Page 13 of 19 Section 3.3.2: if … else Statements The if .. else statement forces a program to execute one statement only if a given condition is true, and a different statement if the condition is false. Syntax of a simple if statement: if (condition) { conditionTrueStatement(s); } else { conditionFalseStatement(s); } nextStatement; When the condition is true, the program executes conditionTrueStatement(s) first, and then nextStatement. When the condition is false, the program executes conditionFalseStatement right away, and then nextStatement. Example: // Get the user’s input for a circle radius System.out.println("Enter the radius of a circle:"); Scanner keyboard = new Scanner(System.in); double radius = keyboard.nextDouble(); double circumference; if (radius < 0.0) { System.out.println("The radius you entered was r = “ + radius); System.out.println("Bad entry; please enter a positive radius"); } else { circumference = 2*Math.PI*radius; System.out.println("For a circle of radius “ + radius + “, the circumference is: " + circumference); } Computer Science Notes Chapter 3 Page 14 of 19 Section 3.3.3: Nested if Statements Nested if statements are used when you want to force the program to execute one of many different statements based on the Boolean values of one or more expressions. Syntax of a simple if statement: Use the syntax of an if … else statement, with the else statements containing additional if … else statements. Example: Compute the letter grade of a numerical score according to the following grading scale: A 92 % - 100 % AB 88 % - 91 % B 82 % - 87 % BC 78 % - 81 % C 72 % - 77 % D 65 % - 71 % F 0 % - 64 % //Convert a number score into a letter Grade System.out.println("Enter a numerical score."); Scanner keyboard = new Scanner(System.in); double score = keyboard.nextDouble(); String letterGrade; if (score >= 91.5) letterGrade = "A"; else if (score >= 87.5) letterGrade = "AB"; else if (score >= 81.5) letterGrade = "B"; else if (score >= 77.5) letterGrade = "BC"; else if (score >= 71.5) letterGrade = "C"; else if (score >= 64.5) letterGrade = "D"; else letterGrade = "F"; System.out.println("A score of " + score + " earns a letter grade of " + letterGrade); Computer Science Notes Chapter 3 Page 15 of 19 Example: Write the Wisconsite/Packer messages using nested if statements instead of compound boolean expressions. Scanner keyboard = new Scanner(System.in); boolean lovePackers = true; boolean loveWisconsin = true; System.out.println("Type true if you love the Packers, "); System.out.println("or type false if you don’t"); lovePackers = keyboard.nextBoolean(); System.out.println("Type true if you love Wisconsin, "); System.out.println("or type false if you don’t"); loveWisconsin = keyboard.nextBoolean(); Scanner keyboard = new Scanner(System.in); boolean lovePackers = true; boolean loveWisconsin = true; System.out.println("Type true if you love the Packers, "); System.out.println("or type false if you don’t"); lovePackers = keyboard.nextBoolean(); System.out.println("Type true if you love Wisconsin, "); System.out.println("or type false if you don’t"); loveWisconsin = keyboard.nextBoolean(); if (loveWisconsin == true && lovePackers == true) System.out.println("You must be a native Wisconsinite."); else if (loveWisconsin == true && lovePackers == false) System.out.println("You must be a Wisconsin immigrant."); if (loveWisconsin == true) if (lovePackers == true) System.out.println("You must be a native."); else System.out.println("You must be an immigrant."); else if (loveWisconsin == false && lovePackers == true) System.out.println("You must be from Minnesota."); else if (loveWisconsin == false && lovePackers == false) System.out.println("You must be from Illinois."); else if (lovePackers == true) System.out.println("You must be from Minnesota."); else System.out.println("You must be from Illinois."); //Exclusive or: if (loveWisconsin ^ lovePackers) System.out.println("That's good enough for me."); //Exclusive or: if (loveWisconsin) if (!lovePackers) System.out.println("That's good enough for me."); else; else if (lovePackers) System.out.println("That's good enough for me."); Section 3.3.4: Example: Computing Taxes Section 3.3.5: Example: An Improved Math Learning Tool Computer Science Notes Chapter 3 Page 16 of 19 Section 3.4: switch Statements switch statements are used when you want to force the program to execute one of many different statements based on the integer values of a single integer expression. Syntax of a simple if statement: switch (integerExpression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)Default; } nextStatement; If the integerExpression evaluates to the number value1, the program executes statement(s)1, and then skips to nextStatement when the break statement is encountered. If the break statement were omitted by accident, the program would execute statement(s)2 next. The same pattern follows for other values of integerExpression. If integerExpression doesn’t evaluate to any of the values, then the statement(s)Default get executed. Notice that parentheses for block statements are not needed after each case… Example: //perform appropriate menu item action switch (menuChoice) { case 't': //Generate quiz questions from the Math Tutor … break; case 'f': //Generate some Math Facts about a number the user enters … break; case 'g': //Convert a number score into a com sci letter Grade … break; case 'c': //Compute the tax on a purchase … break; default: System.out.println("That was not a valid menu choice."); } Computer Science Notes Chapter 3 Page 17 of 19 Section 3.5: Conditional Expressions A shorthand way to assign one of two values to a variable based on a condition Syntax of a conditional expression: variable = booleanExpression ? expression1 : expression2; Traditional way to compute an absolute value: A conditional expression that does the same thing // Get the user’s input for a number System.out.println("Enter a number:"); Scanner keyboard = new Scanner(System.in); double x = keyboard.nextDouble(); // Get the user’s input for a number System.out.println("Enter a number:"); Scanner keyboard = new Scanner(System.in); double x = keyboard.nextDouble(); double abs_x; double abs_x; if (x < 0.0) abs_x = -x; else abs_x = x; abs_x = (x < 0) ? –x : x; Computer Science Notes Chapter 3 Page 18 of 19 Section 3.6: Formatting Console Output and Strings The printf method of the PrintStream class (in the java.io package) allows you to display the values stored in variables in any of several format. The formats you can control include the number of columns used, the number of places after the decimal displayed, and how negative numbers are displayed. The way the printf method works is to replace the variable you want to display in a string with a format specifier (a code that starts with the % character and ends with a letter) that tells the JVM how to display the variable. The variable goes after the string that it is supposed to appear in. Format specifiers may include flags that give additional format information. Example: //the following line produces an output where the format specifier %6.2f will be replaced with the //floating point number 1.5 written using 6 spaces and 2 digits after the decimal point (and followed by a //newline) System.out.printf("Price is: $%6.2f\n", 1.517); //sample output: Price is: $ 1.50 Format Types Code d x o f e g s b c Type Decimal integer Example System.out.printf("%5d", 123); //output: 123 Hexadecimal integer System.out.printf("%5x", 123); //output: 7B Octal integer System.out.printf("%5o", 123); //output: 173 Fixed floating point System.out.printf("%6.2f", 123.); //output:123.00 Exponential floating point System.out.printf("%10.2e", 123.); //output: 1.23e+1 General floating point (printf decides whether to use f System.out.printf("%6.2g", 123); or e) //output:123.00 String System.out.printf("%6s", “123”); //output: 123 Boolean value System.out.printf("%b", lovePackers); //output: true Character value System.out.printf("%c", menuChoice); //output: g Computer Science Notes Chapter 3 Page 19 of 19 Format Flags Flag - Meaning Left justifiation 0 Show leading zeros + Show a + sign for positive numbers ( Enclose negative numbers in parentheses , Show decimal separators Example System.out.printf("%-5dhello", 123); //output:123 hello System.out.printf("%06d", 123); //output:000123 System.out.printf("%+6d", 123); //output: +123 System.out.printf("%(6d", -123); //output: (123) System.out.printf("%10d", 123000); //output: 123,000 Note: to access this functionality use Java version 5.0 or higher. The format method of the String class also recognizes format specifiers. Example: String outputString = String.format("%-5dhello", 123); System.out.println(outputString); //output:123 hello Section 3.7: Operator Precedence and Associativity Precedence Highest Precedence Lowest Precedence Operator Precedence Chart Operator var++ and var-- (Postfix operators) +, (Unary operators) ++var and --var (Prefix operators) (type) (casting) ! (Not) *, /, % +, (Binary addition and subtraction) <, <=, >, >= (Comparison) & (Unconditional and) ^ (Exclusive or) | (Unconditional or) && (Conditional and) || (Conditional or) =, +=, -=, *=, /=, %= (Assignment operators) Section 3.8: Operand Evaluation Order From left to right, according to the operator precedence