Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program, the body contains a main method. Main method header Main method body Special Characters we have seen so far: - Braces define a class body, method body () - Parentheses define the parameters to a method ; - Semi colon end of a statement // - Start a 1 line comment - Pair of double quotes enclose a string of letters - Use single quotes to enclose a character (a-z, A-Z, 0-9, punctuation) Declaration: type name ; Assignment: Variable name on left Operator = in the middle Value on the right Scope lifespan of the variable Start of lifespan - Declaration End of lifespan Closing brace of code block where declared 1
Summary - Arithmetic Operations There are 5 common operations: Addition: + Subtraction: - Multiplication: * Division: / Recall: A B = Quotient * B + Remainder If both operands are integer: produces the quotient Else same as A B Modulus: % (produces the remainder) Summary - Types Primitive Types Variables store the value byte, short, int, long, float, double, boolean, char Reference Types Variables store references to objects, objects stored where in memory String, Scanner, Double, Integer Call methods on object using the dot operator String str = hello ; int numchars = str.length(); Summary - String Declare String str; Create str = Mary ; str = new String( Mary ); Methods to call: int length(); String tolowercase(); String touppercase(); char charat(int position); // position = 0, length - 1 Summary Program Output String (cont) Operator + concatenates two Strings together Concatenate a String and a number and store result in a new String Using print and println to output information to a program. int number = 17; String color = Green ; System.out.println(number); // outputs 17, value of variable System.out.println(color); // outputs Green, value stored in // object referenced by color 2
Summary Scanner (Program Input) Summary - Conversions Import Statement Before class header, add: import java.util.scanner; Declare Scanner keyboard; Create keyboard = new Scanner(System.in); Methods to call: String nextline(); double nextdouble(); int nextint(); Given a String, there are two ways to convert it to a numeric value double Double.parseDouble(String); int Integer.parseInt(String); When will the conversion fail? 340 will convert to int or double abc will cause a run time exception 34.2 will convert to a double Decision Structures Conditional Execution Decision structures allow us to modify the flow of a program We can conditionally execute or conditionally skip one or more statements based on a decision In your first Project, you will extend your TaxComputer program to use decision statements to set the state tax rate based on the the clients state of residence. This project will also use decision statements to determine the taxable income and the amount of federal tax owed. Goal: Send a message to all students enrolled in the Spring term who have not yet paid their tuition. Pseudo-Code: If a student is enrolled in at least one class If they have not paid their tuition Email them a message indicating that their tuition is due. The email should include the balance and the due date. How do we write Java code that performs the sequence above? A message should be sent only if a student is enrolled and if they have not paid their tuition. 3
Java if Statement - Example Example: Converting a Score to a letter Grade boolean tuitiondue = true; if (tuitiondue) System.out.println( Pay your tuition! ); The if-block is all the code in red above. Behavior if is a Java keyword. It is followed by parentheses(). Inside the parentheses is a boolean (has the value of true or false). Flow: when tuitiondue has the value of true, the println is executed. when tuitiondue has the value of false, the println is not executed. Write a program that asks the user to enters 2 exam scores, computes and outputs the average. If the average is at least 97, print a congratulations banner. Pseudo Code Print message for score 1 Read score 1, convert to double Print message for score 2, Read score 2, convert to double Compute average Output average Print message for score 1 Read score 1, convert to double Scanner keyboard = new Scanner(System.in); System.out.print( Please enter the first score: ); String input = keyboard.nextline(); double score1 = Double.parseDouble(input); Compute average Output average double avg = (score1 + score2) / 2; 4
Use a relational operator to compare the value of the variable avg to the value 97. Result is a boolean Read expressions from left to right! Let a and b be two different primitive variables. Assume they have the same primitive type: boolean result = a < b; // result is true if a less than b boolean result = a > b; // result is true if a greater than b boolean result = a <= b; // result is true if a less than, or equal to, b boolean result = a >= b; // result is true if a greater than, or equal to, b boolean result = a == b; // result is true if a equals b boolean result = a!= b; // result is true if a is not equal to b Use a relational operator to compare the value of the variable avg to the value 97. Which is the correct operator to use? at least à greater than or equal à >= if (avg >= 97) System.out.println( Great Job!!! ); Note that we put the expression inside the parentheses. this is the most common approach. Read this as: boolean tmp = avg >= 97; If (tmp).. Java if Statement Java if Statement - continued General Form if (booleanexpression) statement; A booleanexpression evaluates to true or false You can use a boolean variable You can use an expression with a relational operator If we want to conditionally execute multiple statements, use braces to form a code block if (booleanexpression) statement1; statement2; statement3; The if block is the code in red Flow: When the expression is true, the code block defined by the braces is executed When the expression is false, the code block is skipped 5
Last Note on Relational Operators Compute average Output average double avg = (score1 + score2) / 2; if (avg >= 97) System.out.println( Great Job!!! ); if (avg < 97) Relational operators can be used primitive types byte, short, int, long, double, float and char and boolean Let a and b be two different primitive variables. Assume they have the same primitive type: boolean result = a < b; // result is true if a less than b boolean result = a > b; // result is true if a greater than b boolean result = a <= b; // result is true if a less than, or equal to, b boolean result = a >= b; // result is true if a greater than, or equal to, b boolean result = a == b; // result is true if a equals b boolean result = a!= b; // result is true if a is not equal to b See pages 120-121 for examples with char variables. Java if- Statement Java supports a structure that, with one test, allows you to select between two different code paths. if (booleanexpression) statement1; or code block statement2; or code block Flow: When the boolean expression evaluates to true, statement1 is executed. Otherwise, statement 2 is executed. With an if- structure, one of the two statements is always executed. Compute average Output average double avg = (score1 + score2) / 2; if (avg >= 97) System.out.println( Great Job!!! ); 6
Example: Summary if and if- statement Write a Java statement that assigns to the variable rate, the value of 0.20 if the variable income is at least 10000. Otherwise, set the rate to a value of 0.05. if statement: when expression evaluates to true, execute statement if (expression) statement; or code block double rate; // declare the variable, value unknown if (income >= 10000) // why >=? rate = 0.20; rate = 0.05; if statement: when expression evaluates to true, execute statement1 otherwise, execute statement2. if (expression) statement1; or code block statement2; or code block Java if- if [ ] - Example: Using only if- statements To test a series of conditions, you can use nested if- statements. However, it is often easier to use the if statement. Goal: Output a message the prints a letter grade based on the average of 3 exam scores. Use a straight scale. One solution is: if average at least 90, output A if average at least 80, output B if average at least 70, output C output not passing. 7
if (avg >= 90) System.out.println( A ); if (avg >= 80) System.out.println( B ); if (avg >= 70) System.out.println( C ); System.out.println( Not passing ); Example: Using only if- if statements Another solution is: if average at least 90, output A if average at least 80, output B if average at least 70, output C output not passing. Lets write this in Java if (avg >= 90) System.out.println( A ); if (avg >= 80) System.out.println( B ); if (avg >= 70) System.out.println( C ); System.out.println( Not passing ); if (avg >= 90) System.out.println( A ); if (avg >= 80) System.out.println( B ); if (avg >= 70) System.out.println( C ); System.out.println( Not passing ); The if and if keywords are followed by a boolean expression contained in parentheses Only evaluate the expression avg >= 80 when the expression avg >= 90 evaluated to false. Can have as many if clauses as you want. The trailing is optional. 8
if and if- if - statement if statement: when expression evaluates to true, execute statement if (expression) statement; or code block if if statement: when expression evaluates to true, execute statement1 otherwise evaluate anotherexpression. If it evaluates to true, execute statement2 execute statement3. if (expression) statement1; or code block delimited by braces if (anotherexpression) statement2; or code block statement3; or code block A common task in a program is to display a message that asks the user to enter data via the keyboard. The program then reads the data. To display a message, Java programmers use a print or println statement. To read data, Java programmers use a Scanner. Assume: Scanner keyboard; Circle all that are true. a) The variable keyboard is a primitive type. b) The statement creates a Scanner and assigns the value to keyboard: keyboard = new Scanner(System.in); c) The statement creates a Scanner and assigns the value to keyboard: keyboard = new Scanner(System.out); d) Programs that use a Scanner require an import statement be added to the class body. 1/29/2018 d) is false, the import is before the class header. A programmer needs to read a value that the user has entered to be treated as a number. One option is to read the data as: double number = keyboard.nextdouble(); The other option is to read the entire line the user enters. String data = keyboard.nextline(); How can the user convert this data to a double? a) Not possible. b) Use the statement: int val = Integer.parseDouble(); c) Use the statement: double val = Double.parseDouble(); d) Use the statement: double val = Double.parseDouble(data); 1/29/2018 d) is the only true statement. Notice that it is the only one that provides the data to the parse method. 9