Conditional Programming

Similar documents
Chapter 3. Selections

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Conditionals and Loops

Algorithms and Conditionals

BRANCHING if-else statements

Java Flow of Control

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

Topics. Chapter 5. Equality Operators

Java I/O and Control Structures

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Oct Decision Structures cont d

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Java I/O and Control Structures Algorithms in everyday life

Chapter 4: Control Structures I

COMP 202 Java in one week

Lesson 7 Part 2 Flags

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Program Control Flow

Program Control Flow

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

COMP 202. Java in one week

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

More Programming Constructs -- Introduction

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Chapter 4: Conditionals and Loops

CMPT 125: Lecture 4 Conditionals and Loops

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

JAVA OPERATORS GENERAL

CS1004: Intro to CS in Java, Spring 2005

Chapter 4: Conditionals and Loops

Warm-Up: COMP Programming with Iterations 1

CSC 1051 Data Structures and Algorithms I

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Chapter 4: Conditionals and Loops

Lab 8: IF statement. Conditionals and Loops. Copyright 2012 Pearson Education, Inc.

Selections. CSE 114, Computer Science 1 Stony Brook University

What did we talk about last time? Examples switch statements

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Flow of Control. Chapter 3

Selection Statements and operators

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

COMP 202 Java in one week

Control Structures in Java if-else and switch

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

5. Selection: If and Switch Controls

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

Full file at

Flow of Control. Chapter 3

Chapter 3 Selection Statements

Prof. Navrati Saxena TA: Rochak Sachan

Building Java Programs

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Repetition, Looping. While Loop

H212 Introduction to Software Systems Honors

Object-Oriented Programming

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Chapter 1 Lab Algorithms, Errors, and Testing

CSIS 10A Assignment 4 SOLUTIONS

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

What methods does the String class provide for ignoring case sensitive situations?

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

Full file at

Introduction to Computer Programming

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Selection Statements and operators

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Control Structures in Java if-else and switch

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

Introduction to Computer Programming

Computer Science is...

IEEE Floating-Point Representation 1

In this chapter, you will:

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Java Coding 2. Decisions, decisions!

The Java language has a wide variety of modifiers, including the following:

Java Programming Language. 0 A history

Lecture 9. Monday, January 31 CS 205 Programming for the Sciences - Lecture 9 1

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Course Outline. Introduction to java

Selection and Repetition Revisited

1 Short Answer (10 Points Each)

Important Java terminology

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Handout 4 Conditionals. Boolean Expressions.

Transcription:

COMP-202 Conditional Programming

Chapter Outline Control Flow of a Program The if statement The if - else statement Logical Operators The switch statement The conditional operator 2

Introduction So far, all the programs we have written executed all the statements they contained Suppose we want to write a program which asks the user to enter two numbers and then displays only the larger of the two This involves executing certain statements in some circumstances, and different statements in other circumstances 3

Flow of Control By default, the order of statement execution through a method is linear one statement after the other is executed, in textual order (top of page, downwards to end of page) Some programming statements modify that order, allowing us to: decide whether or not to execute a particular statement perform a statement over and over repetitively (while) The order of statement execution is called the flow of control 4

Conditional Statement A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements Conditional statements give us the power to make basic decisions Java's conditional statements are the if statement, the ifelse statement, and the switch statement 5

COMP-202 Conditional Programming Part I The if Statement

The if Statement The if statement has the following syntax: if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. if (condition) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped. 7

If Statement Flow Diagram condition? false true statement 8

Comparison Operators A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to!= not equal to <! less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=) 9

More on Comparison Operators Equality (==) and inequality (!=) operators apply to values that have any type The other comparison operators (<, <=, >, >=) only apply to values which have a numeric type (byte, short, int, long, float, double) or that have type char They do not apply to values that have type boolean Even though the operands of a comparison operator may have various types, the type of the result of the comparison is always the same: boolean This implies that the result of a comparison is always true or false 10

Comparison Operator Examples (1) (denominator == 0) Evaluates to true if denominator is equal to 0, evaluates to false otherwise (denominator!= 0) Evaluates to true if denominator is not equal to 0, evaluates to false otherwise (balance > amount) Evaluates to true if the value of balance is strictly greater than the value of amount, evaluates to false otherwise (balance < amount) Evaluates to true if the value of balance is strictly less than the value of amount, evaluates to false otherwise 11

Comparison Operator Examples (2) (balance >= amount) Evaluates to true if the value of balance is greater than or equal to the value of amount, evaluates to false otherwise Note that using => will not work (balance <= amount) Evaluates to true if the value of balance is less than or equal to the value of amount, evaluates to false otherwise Again, note that using =< will not work 12

if Statement Exercise Complete the main() method of the BusRide class by adding code to check whether the number of passengers is greater than the capacity of the bus If it is, then you should display a message asking for x (where x is the number of passengers in excess of the capacity of the bus) volunteers to travel in "economy class": on the roof Regardless of whether the number of passengers exceeds the capacity of the bus, you should display "Let's go!" after you have displayed whether or not volunteers are needed for "economy class" 13

BusRide.java import java.util.scanner; public class BusRide { } public static void main (String[] args) { final int CAPACITY = 56; int passengers; } Scanner keyboard = new Scanner(System.in); System.out.print("Enter the number of people that want to get on the bus: "); passengers = keyboard.nextint(); // Add your code here 14

The if-else Statement An else clause can be added to an if statement to make it an if-else statement: if (condition) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both 15

if-else Statement Flow Diagram condition? false true statement1 statement2 16 7

if-else Statement Exercise Complete the main() method of the Wages class by adding code to compute the gross earnings of an employee If the employee has worked more than 40 hours during his / her work week, he / she should be paid 1.5 times his / her hourly wage for all hours worked in excess of 40 Can you rewrite your code using only a regular ifstatement (that is, one that does not have an else clause)? 17

Wages.java public static void main (String[] args) { final double RATE = 8.25; // regular pay rate final int STANDARD = 40; // standard hours / week double pay = 0.0; int hours; Scanner keyboard = new Scanner(System.in); System.out.print("Enter number of hours worked:"); hours = keyboard.nextint(); // Add your code here } System.out.println( Your pay is: + pay); 18

Block Statements Several statements can be grouped together into a block statement A block is delimited by braces ( {...} ) A block statement can be used wherever a statement is called for in the Java syntax For example, in an if-else statement, the if portion, or the else portion, or both, could be block statements 19

Block Statements Example if (condition) { } else { Statements executed if condition evaluates to true } Statements executed if condition evaluates to false 20

Block Statements vs. Indentation What will happen if the following code fragment is executed: if (a < b) System.out.println(a); System.out.println(b); The second println() call will be executed regardless of whether the condition evaluates to true or false Syntax determines which clause a statement belongs to Indentation has nothing to do with this Tip #1: Always use block statements with if and if-else statements, even when the block statement contains only one statement Tip #2: Always have consistent indentation 21

Block Statements Example For example, the following code fragment will cause a compilation error: if (condition)! statement1; statement2; else statement3; When the compiler reaches statement2, it will assume that the if is part of an if statement (not an if-else statement), and that statement2 should be executed regardless of whether condition evaluates to true or false Then, when the compiler reaches the else, it will not be able to match it with any if statement, and thus will generate an error 22

Block Statement Exercise Complete the main() method of the GuessGame class by adding code to determine whether the user won or not The player wins if he / she is able to guess the number that the program chose at random If the player wins, you should display a message stating that he / she has won, and the amount of money he / she has won If the player loses, you should display a message stating that he / she has lost, what the number chosen by the program was, and the amount the player has lost Whether the player wins or loses, you should display the amount of money he / she has after playing the game 23

GuessGame.java (1) import java.util.scanner; import java.util.random; public class GuessGame { public static void main(string[] args) { final int UPPER_BOUND = 10; Scanner keyboard = new Scanner(System.in); Random randomsource = new Random(); double money; double betamount; int mynumber; int yournumber; System.out.print("How much money to you have? "); money = keyboard.nextdouble(); // Continued on next slide 24

GuessGame.java (2) } } // Continued from previous slide betamount = keyboard.nextdouble(); mynumber = randomsource.nextint(upper_bound) + 1; System.out.print("I've chosen a number between 1 + and " + UPPER_BOUND + ". Try to guess it: "); yournumber = keyboard.nextint(); // Add your code here 25

Nested if Statements The statement executed as a result of an if statement or else clause could be another if statement These are called nested if statements Indentation does not determine which if and else matches with. It is determined by syntax (i.e. by the order of the clauses or {}) An else clause matches with the nearest if 26

Nested if Statement Example One can write nested if-else statements like this: if (condition1)! if (condition2)!! statement1;! else!! statement2; else! if (condition3)!! statement3;! else!! statement4; 27

Control Flow of Nested if Statement true condition? false condition? false condition? false true true statement1 statement2 statement3 statement4 28

Nested if Statement Exercise Complete the main() method of the MinOfThree class by adding code which determines which of the three numbers entered by the user is the smallest number, and displays that number Can you write this code both with and without using block statements? 29

MinimumOfThree.java public static void main(string[] args) { int num1, num2, num3, min = 0; Scanner scan = new Scanner(System.in); System.out.println("Enter three integers: "); num1 = scan.nextint(); num2 = scan.nextint(); num3 = scan.nextint(); // add code here } System.out.println("Minimum value: " + min); 30

More Than Two Execution Branches Nested statements are needed when there are more than two branches / conditions An if-(else-if)-else statement allows several execution branches. if (condition) { statement1; } else if (condition) { statement2; } else { statement3; } if (condition) { statement1; } else { if (condition) { statement2; } else { statement3; } } 31

COMP-202 Conditional Programming Part II Logical Operators

Boolean Expressions Like an arithmetic expression, a boolean expression is a combinations of operators and operands, and it evaluates to a boolean value (i.e. true or false) A boolean expression can be: The comparison of two values using a comparison operator A variable which has type boolean A literal which has type boolean (true or false) The negation of another boolean expression using the! operator The combination of two or more other boolean expressions using the && or operators 33

Comparison Operator Precedence Comparison operators have lower precedence than arithmetic operators, but higher precedence than the assignment operator Therefore, the order of evaluation for this code fragment is the following (assume that a, c, d, and e have a numeric type): boolean b = a > c * d + e; 1 3 2 4 34

Comparing Characters We can use the logical operators on character data The results are based on the Unicode character set The following condition is true because the character '+' comes before the character 'J' in Unicode: if ('+' < 'J') System.out.println ("+ is less than J"); The uppercase alphabet (A-Z) and the lowercase alphabet (a-z) both appear in alphabetical order in Unicode 35

Comparing Characters (2) In the Unicode character set, the numbers assigned to upper-case alphabetic characters ('A' - 'Z'), lower-case alphabetic characters ('a' - 'z') and digits ('0' - '9') not only follow the expected order, but are consecutive If 'A' is assigned the number x, then 'B' is assigned the number x + 1, 'C' is assigned the number x + 2,... If 'a' is assigned the number y, then 'b' is assigned the number y + 1, 'c' is assigned the number y + 2,... If '0' is assigned the number z, then '1' is assigned the number z + 1, '2' is assigned the number z + 2,... Do not hesitate to use this property of characters in your programs 36

Comparing Strings In Java, the String class represents a sequence of characters A character string in Java is an object We cannot use the logical operators to compare objects The equals method can be called on a String to determine if two strings contain exactly the same characters in the same order (even constants) The String class also contains a method called compareto to determine if one string comes before another alphabetically (as determined by the Unicode character set) 37

Comparing Floating Point Values We also have to be careful when comparing two floating point values (float or double) for equality You should rarely use the equality operator (==) when comparing two floats In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal Therefore, to determine the equality of two floats, you may want to check if their difference is below a certain threshold: if (Math.abs(f1 - f2) < 0.00001) System.out.println( Essentially equal ); 38

Logical Operators Boolean expressions can also use the following logical operators:! logical not && logical and logical or All three operators take operands of type boolean and produce results of type boolean Logical not is a unary operator (it has one operand), but logical and and logical or are binary operators (they each have two operands) 39

Logical Operator Examples! boolean choice = false;! if (!choice) System.out.println( Go );! else System.out.println( Stop );! if (!(x>5))! if ( (x>5) && (y<10) )!! choice = true;! else!! choice = false; unary unary binary 40

Logical not The logical not operation is also called logical negation or logical complement If some boolean condition a is true, then!a is false; if a is false, then!a is true Logical expressions can be shown using truth tables a!a true false false true 41

Logical and and or and xor The logical and expression a && b is true if both a and b are true, and false otherwise The logical or expression a b is true if a or b or both are true, and false otherwise The logical xor expression a ^ b is true if a or b are different, and false if a and b are equal 42

Logical and and or and xor Truth Table Since && and and ^ each have two operands, there are four possible combinations of true and false a b a && b a b a ^ b true true true true false true false false true true false true false true true false false false false false 43

Logical Operator Precedence (1) Like arithmetic operators, logical operators have precedence rules among themselves Logical operator! has higher precedence than logical operator &&, and logical operator && has higher precedence than logical operator Consider the following expression (assume that a, b, and c are all of type boolean): a b &&!c 1 2 3 44

Logical Operator Precedence (2) Logical operators also have precedence rules relative to other kinds of operators Logical operators have lower precedence than comparison operators, but higher precedence than the assignment operator Therefore, the order of evaluation for this code fragment is the following (assume that a has type boolean): boolean b = a && c < d; 1 2 3 45

Short-Circuit Evaluation Logical operators && and are evaluated in short-circuit If the first operand of a && operator evaluates to false, the second operand is not evaluated There is no need to do so considering that a logical and expression always evaluates to false as soon as one of its operands evaluates to false Likewise, if the first operand of a operator evaluates to true, the second operand is not evaluated Again, there is no need to do so considering that a logical or expression always evaluates to true as soon as one of its operands evaluates to true 46

Boolean Expression Exercises (1) Write boolean expressions that evaluates to true if and only if the given condition is true The absolute value of variable a (of type int) is greater than 100 The values of variables a, b, and c are all different The character stored in either variable c1, or variable c2 (both of type char), or both, is a digit 47

Boolean Expression Answers (1) Write boolean expressions that evaluates to true if and only if the given condition is true The absolute value of variable a (of type int) is greater than 100 (a > 100) (a < -100) The values of variables a, b, and c are all different (a!= b) && (b!= c) && (a!= c) or!((a == b) (b == c) (a == c)) The character stored in either variable c1, or variable c2 (both of type char), or both, is a digit (('0' <= c1) && (c1 <= '9')) (('0' <= c2) && (c2 <= '9')) 48

Boolean Expression Exercises (2) Write boolean expressions that evaluates to true if and only if the given condition is true The value stored in exactly one of the two variables a and b (both of type int) is equal to 0 49

Boolean Expression Exercises (2) Write boolean expressions that evaluates to true if and only if the given condition is true The value stored in exactly one of the two variables a and b (both of type int) is equal to 0 ((a == 0) && (b!= 0)) ((b == 0) && (a!= 0)) or (a == 0) ^ (b == 0) 50

COMP-202 Conditional Programming Part III The switch Statement

The switch Statement The switch statement provides another means to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to the case associated with the first value that it matches with (first come, first serve) 52

switch Statement Syntax The general syntax of a switch statement is the following: switch and case are reserved words expression is evaluated and compared to value1, then value2, etc... switch (expression) {! case value1:!! statement-list1; If expression evaluates to! case value2: value2, control jumps to!! statement-list2; statement-list2! case value3:!! statement-list3;! // As many cases as needed } 53

The break Statement Often a break statement is used as the last statement in each case's statement list break is also a reserved word in Java A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case, regardless of whether the value of the expression in the switch matches that case Sometimes this can be helpful, but usually we only want to execute the statements associated with one case 54

Control Flow of switch Statement value1 value2 evaluate expression value...... valuen statementlist1 statementlist2 statementlist3 55

Control Flow of switch with break value1 value2 evaluate expression value...... valuen statementlist1 statementlst2+break statementlist3 56

switch Statement Example int age; System.out.print("Enter your age: "); age = keyboard.nextint(); switch(age) { case 5: System.out.println("Five years old"); break; } case 10: age++; System.out.println(age); case 20: age--; System.out.println(age); What happens when the value of age is: 5? 10? 20? 3 or any other number? 57

switch Statement default case A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it for all values which do not match a case Because of this, though the default case can be positioned anywhere in the switch statement, it is usually placed at the end If there is no default case, and no other value matches, control falls through to the statement after the switch 58

switch with default Control Flow value1 value2 statementlst1+break statementlst2+break evaluate expression value...... any other value def-state ment-lst 59

switch without default value1 value2 statementlst1+break statementlst2+break evaluate expression value...... any other value 60

default Case Example int section; System.out.print("Enter your COMP-202 section: "); section = keyboard.nextint(); switch(section) { case 1: case 3: System.out.println("Your instructor s name is Dan."); break; case 2: System.out.println("Your instructor s name is Jörg."); break; default: System.out.println("How can that be?"); } 61

default Case: Watch Out! int section; System.out.print("Enter your COMP-202 section: "); section = keyboard.nextint(); switch(section) { default: System.out.println("How can that be?"); case 1: case 3: System.out.println("Your instructor s name is Dan."); break; case 2: System.out.println("Your instructor s name is Jörg."); break; } What happens now? 62

More on switch Statements The expression of a switch statement must evaluate to a value of type char, byte, short or int; it cannot be a floating point value, a long, a boolean or a String Note that the implicit boolean expression in a switch statement is equality (it is never <, <=, >, nor >=) You cannot perform relational checks with a switch statement The value of each case must be a constant It cannot be a variable 63

switch Statement Exercise (1) Complete the main() method of the Drinks class by adding code that does the following: If the user indicates that he / she wants to drink orange juice, the program should display two messages: "Vitamin C!" and "Your bones will thank you." If the user indicates that he / she wants to drink milk, the program should display "Your bones will thank you." If the user indicates that he / she wants to drink water, the program should display "The classics never die." 64

switch Statement Exercise (2) If the user indicates that he / she wants to drink wine, the program display a prompt asking him / her whether he wants red or white wine, and read the answer If the user chooses red wine, the program should display "Good for your heart." If the user chooses white wine, the program should display "Good for your lungs." If the user indicates that he / she wants beer, the program should display "Watch that belly!" If the user enters an invalid option, the program should display "That's not going to quench your thirst..." 65

Drinks.java public static void main(string[] args) { Scanner keyboard; int choice; } keyboard = new Scanner(System.in); System.out.println("Here is the drinks menu : "); System.out.println("1. Orange juice"); System.out.println("2. Milk"); System.out.println("3. Water"); System.out.println("4. Wine"); System.out.println("5. Beer"); System.out.print("What will it be? "); choice = keyboard.nextint(); // Add your code here 66

COMP-202 Conditional Programming Part IV The Conditional Operator

The Conditional Operator Java has a conditional operator that evaluates a boolean expression One of two other expressions is evaluated based on the result of the evaluation of that boolean expression The result of the chosen expression is the result of the entire conditional operator Its syntax is the following: condition? expression1 : expression2 If condition evaluates to true, then expression1 is evaluated; if it evaluates to false, then expression2 is evaluated 68

Conditional Operator Examples (1) The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = (num1 > num2)? num1 : num2; If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary, meaning that it requires three operands 69

Conditional Operator Examples (2) Another example: System.out.println("Your change is " + count + " dime" +! ((count == 1)? "" : "s")); If count evaluates to 1, then "dime" is printed If count evaluates to any value other than 1, then an "s" is added at the end of "dime" 70

Conditional Operator Exercise (1) Complete the main() method of the MoreWages class by adding code to compute the gross earnings of an employee If the employee has worked more than 40 hours during his / her work week, he / she should be paid 1.5 times his / her hourly wage for all hours worked in excess of 40 Use the conditional operator to determine whether the employee has worked more than 40 hours in his / her work week 71

MoreWages.java public static void main (String[] args) { final double RATE = 8.25; // regular pay rate final int STANDARD = 40; // standard hours / week double pay = 0.0; int hours; Scanner keyboard = new Scanner(System.in); System.out.print("Enter number of hours worked:"); hours = keyboard.nextint(); // Add your code here } System.out.println( Your pay is: + pay); 72

COMP-202 Conditional Programming Exercises

Conditional Programming Exercises (1) Write a program which consists of a single class called OldEnough that asks the user for their age and displays "You can enter" if he/she is over 18, but displays "Sorry, you are not allowed to enter" otherwise. Write a program which consists of a single class called BuyStuff that asks the user for two amounts, adds them, calculates tax at 15%, shows the result to the user, and asks for money. It then compares if the person gave enough money. If so, it displays the amount of change to return otherwise it displays a message asking for more money. 74

Conditional Programming Exercises (2) Write a program which consists of a single class called Calculator. This program will display a menu with the following options: (1) add, (2) subtract, (3) multiply, (4) divide (5) mod, and (6) do nothing. If the user enters something else, the program should display an error message. Otherwise, it should ask the user for two numbers, perform the calculation, and display the result. Write a program which consists of a single class called SortThree. This program should ask the user to enter 3 integers. The program will then display these in increasing order. 75