CSS 161 Fundamentals of Compu3ng Assignments, Expressions, Operators, Console input & output October 1, 2012 Instructor: Uma Murthy CSS SKL 161 A Instructor: Joe McCarthy
Outline Introduc3on Recap, reminders Assignments, expressions, and operators Console input and output
Who am I? Uma Murthy, Ph.D. o Lecturer, Compu3ng and SoPware Systems, UWB o Naming conven3ons Uma Professor Murthy Dr. Murthy
Background Ph.D. from Virginia Tech, 2011 o Digital libraries, informa3on retrieval, personal informa3on management Research associate, Kenan Ins3tute, UNC- Chapel Hill o SoPware agents SoPware Developer, IBM o Incuba3on projects, mainframe emulator (Java development) Master s in Computer Applica3ons, Na3onal Ins3tute of Technology, Trichy, India Bachelor s in Electronics, Bangalore University, India
Current Lecturer, Compu3ng and sopware systems, UWB Human Factors Engineer, URCVentures o 3- dimensional reconstruc3on from image sets o Assessing technology and evalua3ng usability
Recap
Updates/ reminders Assigned readings o Any material in assigned readings is poten3al fodder for exams, regardless of whether we cover it in a lecture, lab or assignment Slides will always be posted on web site o Typically, shortly aper each class Please complete survey if not already done
Homework 1 Available by 5pm today, due midnight, Mon, Oct 8
Required Textbook Absolute Java, 5 th Edition Walter Savitch & Kenrick Mock Addison-Wesley, 2013 4 th Edition OK, too
Supplemental Material (1/2) Java: An Introduction to Problem Solving & Programming, 6th Edition Walter Savitch Addison-Wesley, 2012 http://courses.washington.edu/css161/joemcc/notes/ SavitchCh01.pdf (access via Notes link on course homepage) CSS 161: Fundamentals of Compu3ng
Supplemental material (2/2) Prac3ce It! hfp://webster.cs.washington.edu:8080/prac3ceit/ Sign up for a Prac3ce- It account o Make sure to use the school value, "University of Washington Bothell o Add the course, "CSS 161A Autumn 2012 Uma Murthy", to your list of enrolled courses for your account You can do this by clicking My Courses, then Add Course.
Java Goal: o o o Write once, run anywhere JDK: Java Developers Kit JRE: Java Run3me Environment Edi3ons o o o o SE: Standard Edi+on EE: Enterprise Edi3on ME: Micro Edi3on (mobile, embedded) Embedded: flash memory, closed systems Versions o 1.0 (1992),.. 1.6 (2006), 1.7 (2011)
Downloading Java [op3onal] hfp://www.java.com/getjava/ o Current: Version 7 update 7 (1.7u7) On Mac, requires Mac OS X 10.7.3 or higher o Can also use Version 6 update 35 (1.6u35) hfp://www.java.com/en/download/manual_v6.jsp Supported thru February 2013 We will be wri3ng Java, so we want JDK o Which includes JRE
Integrated Development Environments (IDEs) Programming tools o Edit text (code) + compile + run o Graphical representa3ons of components We ll be using BlueJ, but you can use others bluej.org eclipse.org netbeans.org
Downloading BlueJ http://www.bluej.org/download/download.html
Recap Computer program?
Recap Computer program? o Set of instruc3ons that tell a computer to execute some task
Recap: Intro to Java Class Method main() Iden3fier Reserved word Variable Declara3on Assignment Operator System.out.println() Output: 10 + 20 = 30
Recap: Intro to Java Class Method main() Iden3fier Reserved word Variable Declara3on Assignment Operator System.out.println() Output: 10 + 20 = 30
Assignments & Expressions Syntax: variable = expression Seman3cs: Evaluate expression, assign value to variable Expression: Constant (1, 1.23, 3.45e6, a, css161, true, false) final static int COURSENUMBER = 161; Variable (num2) expression operator expression Operators: *, /, % +, -
Operators & Precedence Can use parentheses to change precedence 1 + 2 * 3 (1 + 2) * 3 When operators in an expression have the same precedence, the expression is evaluated from lep to right.
Integer division int x = 4; int y = 7; int z = y/x; System.out.println(z); Answer: 1 In integer division, the result is only the integer part and the part aper the decimal is discarded.
Focus only on these for now
Shorthand assignments Example: Equivalent To: count += 2; count = count + 2; sum -= discount; sum = sum discount; bonus *= 2; bonus = bonus * 2; time /= rushfactor; time = time / rushfactor; change %= 100; change = change % 100; amount *= count1 + count2; amount = amount * (count1 + count2);
Increment & Decrement Operators Syntax: variable++ ++variable variable- - - - variable Note: can be applied only to a single variable Seman3cs: Set variable to next / previous value Examples int num1 = 1; char char1 = B ; num1++; char1--; Precedence: increment/decrement before/aper use 2*(++num1) 4 2*(num1++) 2
Longer expressions with unary operators int y = 3; System.out.println((y++ + y++ + y--)); System.out.println(y);
Longer expressions with unary operators int y = 3; System.out.println((y++ + y++ + y--)); System.out.println(y); Answer: 12 4
Longer expressions with unary operators int y = 3; System.out.println((y++ + y++ + y--)); (y=3) 3 System.out.println(y); Answer: 12 4
Longer expressions with unary operators int y = 3; System.out.println((y++ + y++ + y--)); (y=3) (y=4) 3 + 4 System.out.println(y); Answer: 12 4
Longer expressions with unary operators int y = 3; System.out.println((y++ + y++ + y--)); (y=3) (y=4) (y=5) 3 + 4 + 5 y = y 1; System.out.println(y); Answer: 12 4
Longer expressions with unary operators int y = 3; System.out.println((y++ + y++ + y--)); (y=3) (y=4) (y=5) 3 + 4 + 5 y = y 1; System.out.println(y); Answer: 12 4 (y=4)
Assignment Compa3bility double float long int short byte char
Assignment compatability OK int num1 = 23; int num2 = 'a'; double real1 = 23; Not OK int num3 = 23.0; char c = 1200000; double float long int short byte char
Type cas3ng & coercion Syntax: variable = (type) expression Seman3cs Convert expression to type, assign value to variable Only allowed if expression type is compa3ble with variable type Type coercion: Automa3c type cas3ng: double float int Examples short num3 = (short) A ; int num4 = (int) 1.9; //truncate to 1 double num5 = 123; // coercion int num6 = 1.23; // error
Console Input & Output System.out A Java object associated with the console (screen) print(), println() Methods associated with the System.out object Syntax: System.out.print(expression) System.out.println([expression]) Seman3cs: Evaluate expression, output its value println: expression is op3onal (hence the square brackets []) output a carriage return / line feed (newline) at end of line
Formafed output: printf Syntax: System.out.printf(format[,expression]*) Seman3cs: Use format string to output expression(s) Examples: System.out.printf( Hello ); System.out.printf( Hello\n ); System.out.printf( %5.1f, 1.25); System.out.printf( %-5.1f, 1.25); System.out.printf( $.2f, 1.2);
Format string specifiers
Console input: Scanner class Not built- in, have to import import java.util.scanner; Next: create an instance of the class Syntax: classname variable = new classname([args]) Seman3cs: Create an instance of classname, ini3alize it with args, assign instance to variable Example: Scanner keyboard = new Scanner(System.in); Create an instance of the Scanner class (in java.u3l package) Ini3alize it to accept input from the system console (System.in) Assign it to keyboard (NB: keyboard not a reserved word)
Console Input Using the Scanner Class The method nextint reads one int value typed in at the keyboard and assigns it to a variable: int numberofpods = keyboard.nextint(); The method nextdouble reads one double value typed in at the keyboard and assigns it to a variable: double d1 = keyboard.nextdouble(); Mul3ple inputs must be separated by whitespace and read by mul3ple invoca3ons of the appropriate method o Whitespace is any string of characters, such as blank spaces, tabs, and line breaks that print out as white space 2-41 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Console Input Using the Scanner Class The method next reads one string of non- whitespace characters delimited by whitespace characters such as blanks or the beginning or end of a line Given the code String word1 = keyboard.next(); String word2 = keyboard.next(); and the input line jelly beans The value of word1 would be jelly, and the value of word2 would be beans 2-42 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Console Input Using the Scanner Class The method nextline reads an en3re line of keyboard input The code, String line = keyboard.nextline(); reads in an en3re line and places the string that is read into the variable line The end of an input line is indicated by the escape sequence '\n' o This is the character input when the Enter key is pressed o On the screen it is indicated by the ending of one line and the beginning of the next line When nextline reads a line of text, it reads the '\n' character, so the next reading of input begins on the next line o However, the '\n' does not become part of the string value returned (e.g., the string named by the variable line above does not end with the '\n' character) 2-43 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Keyboard Input Demonstra3on (Part 1 of 2) 2-44 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Keyboard Input Demonstra3on (Part 2 of 2) 2-45 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Another Keyboard Input Demonstra3on (Part 1 of 3) 2-46 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Another Keyboard Input Demonstra3on (Part 2 of 3) 2-47 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Another Keyboard Input Demonstra3on (Part 3 of 3) 2-48 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Lecture 4 stopped here Prac3ce it problems done in class o Self- check 1.6 Legal iden3fiers o Self- check 2.1 Legal in literals o Self- check 2.2 Expressions Prac3ce it problems to try by yourself o Self- check 2.3 (note that some problems have decimal numbers and hence will follow decimal division)
Pi}all: Dealing with the Line Terminator, '\n' The method nextline of the class Scanner reads the remainder of a line of text star3ng wherever the last keyboard reading lep off This can cause problems when combining it with different methods for reading from the keyboard such as nextint Given the code, Scanner keyboard = new Scanner(System.in); int n = keyboard.nextint(); String s1 = keyboard.nextline(); String s2 = keyboard.nextline(); and the input, 2 Heads are better than 1 head. what are the values of n, s1, and s2? 2-50 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Pi}all: Dealing with the Line Terminator, '\n' Given the code and input on the previous slide n will be equal to "2", s1 will be equal to "", and s2 will be equal to "heads are better than" If the following results were desired instead n equal to "2", s1 equal to "heads are better than", and s2 equal to "1 head" then an extra invoca3on of nextline would be needed to get rid of the end of line character ('\n') 2-51 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Methods in the Class Scanner (Part 1 of 3) 2-52 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Methods in the Class Scanner (Part 2 of 3) 2-53 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Methods in the Class Scanner (Part 3 of 3) 2-54 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Java Documenta3on for Scanner hfp://download.oracle.com/javase/6/docs/api/java/u3l/scanner.html
Programming Tip: Prompt for Input A program should always prompt the user when he or she needs to input some data: System.out.println( "Enter the number of pods followed by"); System.out.println( "the number of peas in a pod:"); 2-56 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Programming Tip: Echo Input Always echo all input that a program receives from the keyboard In this way a user can check that he or she has entered the input correctly o Even though the input is automa3cally displayed as the user enters it, echoing the input may expose subtle errors (such as entering the lefer "O" instead of a zero) 2-57 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Self- Service Checkout Line (Part 1 of 2) 2-58 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Self- Service Checkout Line (Part 2 of 2) 2-59 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
The Empty String A string can have any number of characters, including zero characters o "" is the empty string When a program executes the nextline method to read a line of text, and the user types nothing on the line but presses the Enter key, then the nextline Method reads the empty string 2-60 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Other Input Delimiters The delimiters that separate keyboard input can be changed when using the Scanner class For example, the following code could be used to create a Scanner object and change the delimiter from whitespace to "##" Scanner keyboard2 = new Scanner(System.in); Keyboard2.useDelimiter("##"); APer invoca3on of the usedelimiter method, "##" and not whitespace will be the only input delimiter for the input object keyboard2 2-61 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Changing the Input Delimiter (Part 1 of 3) 2-62 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Changing the Input Delimiter (Part 2 of 3) 2-63 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Changing the Input Delimiter (Part 3 of 3) 2-64 Copyright 2010 Pearson Addison- Wesley. All rights reserved.
Branching mechanism Next Time