Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete. We did not review this in lecture. User Input Java Scanner We have covered how to give information to the user print and println statements. How can we get information from the user? Let s solve a simpler problem how can we get information from the keyboard? Java Scanner class defines all of the functionality needed to read from the keyboard and pass that information on to your program Scanner is a object (just like the String is an object). Scanner will be the type in a variable declaration. Step 0: Add a statement to include the Java Scanner library in our program. Put before the class header. import java.util.scanner; Step 1: Declare a reference to a Scanner Scanner keyboard; Step 2: Create a Scanner object in memory and assign the address to the variable keyboard. 1
Java Scanner Step 2: Create a Scanner object in memory and assign the address to the variable keyboard. new is a Java keyword, it causes creation. We are telling it to create a Scanner object. The parentheses () indicate this is a method call. We saw these before. We are passing the argument System.in to the method. This is the data given to the method. System.in means the console or your keyboard in Java = is the assignment operator. We are assigning the address of the Scanner object to keyboard. Using the Scanner (Read 2.13!) To read sequence of characters until a carriage return, we call the method nextline(). String nextline() Example: Ask a client to enter their name and print a welcome banner System.out.print( Please enter your name: ); String clientname = keyboard.nextline(); System.out.println( Welcome + clientname); Questions: Why was print used instead of println? What difference does it make? What is the type of clientname? What methods can we call on clientname? What are the parameters of the method nextline()? What type does nextline() return? To answer this, ask yourself, the type of clientname Using the Scanner (Read 2.13!) Reading Numerical Values (book, pg 96) Example: Compute a person s BMI Pseudo Code BMI = weight in kilograms / square of the height in meters Ask for the persons weight in KGs Ask for the persons height (in meters) Compute the BMI Print the BM To read sequence of characters until a carriage return, we call the method nextline(). String nextline() How can we read a number? Java provides two different options. Directly read a numerical value Read a String using nextline() and convert the String to its numerical equivalent Solution 1: Read in numerical values. System.out.print( Please enter your weight in KGs: ); double weightinkgs = keyboard.nextdouble(); System.out.print( Please enter your height in meters: ); double heightinmeters = keyboard.nextdouble(); Using nextdouble() (or nextint()) leaves the carriage return in the input stream. This causes problems when used with nextline() commands. See your book for a detailed discussion. 2
Reading Numerical Values (book, pg 96) Solution 2: Read in all data until carriage return and convert System.out.print( Please enter your weight in KGs: ); String weightinkgs = keyboard.nextline(); System.out.print( Please enter your height in meters: ); String heightinmeters = keyboard.nextline(); double weight = Double.parseDouble(weightInKGs); double height = Double.parseDouble(heightInMeters); Using nextline to read keyboard input, so the entire contents until the carriage return is stored in weightinkgs Less error-prone approach than directly reading ints... Double, Integer, String, Scanner,. Java Classes we have see so far: String Used to store a sequence of characters. Scanner Used for reading keyboard input Double Used to convert a String into double value Integer Used to convert a String into an int value Scope Variables have scope lifespan of the variable Start of lifespan - Declaration End of lifespan Closing brace } of code block where declared Summary Program Parts 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) 3
Summary - Variables 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 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 elsewhere 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 ); // str s value is undefined Methods to call: int length(); String tolowercase(); String touppercase(); char charat(int position); // position = 0, length() - 1 4
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 Summary Scanner (Program Input) 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(); Summary - Conversions 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 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. 5
Conditional Execution 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. Java if Statement - Example boolean tuitiondue = true; if (tuitiondue) System.out.println( Pay your tuition! ); 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. Example: Converting a Score to a letter Grade 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 If the average is at least 97, output a congratulations message Print message for score 1 Read score 1, convert to double System.out.print( Please enter the first score: ); String input = keyboard.nextline(); double score1 = Double.parseDouble(input); 6
Compute average Output average double avg = (score1 + score2) / 2; System.out.println( Your average is: + avg); If the average is at least 97, output a congratulations message 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 Java if Statement If the average is at least 97, output a congratulations message 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).. 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 7
Java if Statement - continued If we want to conditionally execute multiple statements, use braces {} to form a code block if (booleanexpression) { statement1; statement2; statement3; } 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 Compute average Output average If the average is at least 97, output a congratulations message double avg = (score1 + score2) / 2; if (avg >= 97) { } System.out.println( Your average is: + avg); System.out.println( Great Job!!! ); if (avg < 97) System.out.println( Your average is: + avg); Last Note on Relational Operators 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. 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. a) is false, keyboard is a reference to a Scanner. d) is false, import is before the class body. 1/29/2018 8
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); d) is the only true statement. We need to give the Double object method parsedouble() what is to be parsed. The variable data points to what is to be parsed. 1/29/2018 9