COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand
COSC 236 Web Site You will always find the course material at: http://www.class-notes.us or http://www.class-notes.info or http://www.lecture-notes.tripod.com From this site you can click on the COSC-236 tab to download the PowerPoint lectures, the Quiz solutions and the Laboratory assignments. 2
Lecture 05 2/10/2014 3
Review of Quiz 8 4
Review of Quiz 8 Key items you need to know from this quiz: How to pass parameters from the calling program to the called program How to set up a for loop to count the rows How to set up a for loop to count the columns Where to put the three print statements: System.out.print( ) to print the matrix elements System.out.println() to create new line after each row System.out.println() to create new line after each matrix 5
Review of Quiz 8 Main method calls the method matrix with the actual parameters to specify each of the three matrices: public class Quiz8 { public static void main (String[] args){ matrix('a', 3, 4); //Print 3x4 a matrix matrix('b', 5, 5); //Print 5x5 b matrix matrix('c', 4, 3); //Print 4x3 c matrix } public static void matrix(char sym, int row, int col) 6
Review of Quiz 8 Main method calls the method matrix with the actual parameters to specify each of the three matrices: public class Quiz8 { public static void main (String[] args){ matrix('a', 3, 4); //Print 3x4 a matrix matrix('b', 5, 5); //Print 5x5 b matrix matrix('c', 4, 3); //Print 4x3 c matrix } public static void matrix(char sym, int row, int col) 7
Review of Quiz 8 Main method calls the method matrix with the actual parameters to specify each of the three matrices: public class Quiz8 { public static void main (String[] args){ matrix('a', 3, 4); //Print 3x4 a matrix matrix('b', 5, 5); //Print 5x5 b matrix matrix('c', 4, 3); //Print 4x3 c matrix } public static void matrix(char sym, int row, int col) 8
Review of Quiz 8 Main method calls the method matrix with the actual parameters to specify each of the three matrices: Actual Parameters public class Quiz8 { public static void main (String[] args){ matrix('a', 3, 4); //Print 3x4 a matrix matrix('b', 5, 5); //Print 5x5 b matrix matrix('c', 4, 3); //Print 4x3 c matrix } Formal Parameters public static void matrix(char sym, int row, int col) 9
Review of Quiz 8 The method matrix copies the values of the actual parameters into its formal paramenters: sym, row and col matrix('a', 3, 4); a 3 4 public static void matrix(char sym, int row, int col) { for (int i = 1; i <= row; i++) { //i counts the rows for (int j = 1; j <= col; j++) { //j counts the columns System.out.print(sym + "(" + i + ", " + j + ") "); } //NOTE: this ends the printing of one row System.out.println(); //New line after each row } //NOTE: this ends the printing of the entire matrix System.out.println(); //New line after each matrix } 10
Review of Quiz 8 (The entire program) 11
Review of Quiz 8 (The printout) 12
Quiz 8 (Solution) 13
Objects and Classes; Strings (pp. 159-160) We ve spent a considerable amount of time discussing the primitive types in Java and how they work, so it s about time that we started talking about objects and how they work. The idea for objects came from the observation that as we start working with new kinds of data (integers, reals, characters, text, etc.), we find ourselves writing a lot of methods that operate on that data. Rather than completely separating the basic operations from the data, it seemed to make sense to include them together. This packaging of data and operations into one entity is the central idea behind objects. An object stores some data and has methods that act on its data. 14
Classes and objects (p. 160) class: A program entity that represents either: 1. A program / module, or 2. A type of object. A class is a blueprint or template for constructing objects. Example: The DrawingPanel class (type) is a template for creating many DrawingPanel objects (windows). Java has 1000s of classes. Later (Ch.8) we will write our own. object: An entity that combines data and behavior. object-oriented programming (OOP): Programs that perform their behavior as interactions between objects. 15
Objects (p. 160) object: An entity that contains data and behavior. data: behavior: variables inside the object methods inside the object You interact with the methods; the data is hidden in the object. Constructing (creating) an object: Type objectname = new Type(parameters); Calling an object's method: objectname.methodname(parameters); 16
Using Class as a Blueprint for Objects (p. 160) A class is like a blueprint of what the object looks like. Once you ve given Java the blueprint, you can ask it to create actual objects that match that blueprint. We refer to the individual objects as instances of the class. Often people use the words instance and object interchangeably. This concept classes as blueprints for objects is difficult to understand in the abstract. Don't worry too much about this in COSC-236 -- it is the subject of COSC-237 However, to give a brief introduction to what it means and how it works, we ll look at several different pre-defined Java classes. In keeping with our idea of focusing on fundamental concepts first, in this chapter we ll study how to use existing objects that are already part of Java. We will leave the issue of how to define our own new types of objects for COSC-237. 17
Blueprint analogy (p. 160) state: current song volume battery life behavior: power on/off change station/song change volume choose random song ipod blueprint/factory creates ipod #1 state: song = "1,000,000 Miles" volume = 17 battery life = 2.5 hrs behavior: power on/off change station/song change volume choose random song ipod #2 state: song = "Letting You" volume = 9 battery life = 3.41 hrs behavior: power on/off change station/song change volume choose random song ipod #3 state: song = "Discipline" volume = 24 battery life = 1.8 hrs behavior: power on/off change station/song change volume choose random song 18
Classes and objects (p. 160) Using objects differs from using primitive types We ll have to introduce some new syntax and concepts. It would be nice if Java had a consistent model for using all types of data, but Java doesn t. If you want to understand how your programs operate, you ll have to learn two sets of rules: One for primitives A different one for objects. 19
Strings as and example of objects (p. 160-166) Let s use strings as our example of an object We already know some of the syntax and concepts. Let s look at what we know in the new context of classes and objects. Strings are an example of objects: Strings contain data (the characters) Strings contain behavior (methods this is the new part). 20
Strings (pp. 160-166) string: An object storing a sequence of text characters. Unlike most other objects, a String is not created with new. String name = "text"; String name = expression; (using the + concatenation) Examples: String name = "Marla Singer"; int x = 3; int y = 5; String point = "(" + x + ", " + y + ")"; 21
Behavior: Methods associated with strings (Indexes) Characters of a string are numbered with 0-based indexes: String name = "R. Kelly"; index 0 1 2 3 4 5 6 7 character R. K e l l y First character's index : 0 Last character's index : 1 less than the string's length The individual characters are values of type char (seen later) 22
String methods (p. 166) indexof(str) length() Method name substring(index1, index2) or substring(index1) tolowercase() touppercase() Description index where the start of the given string appears in this string (-1 if not found) number of characters in this string the characters in this string from index1 (inclusive) to index2 (exclusive); if index2 is omitted, grabs till end of string a new string with all lowercase letters a new string with all uppercase letters These methods are called using the dot notation: String gangsta = "Dr. Dre"; System.out.println(gangsta.length()); // 7 23
String method examples (p. 166) // index 012345678901 String s1 = "Stuart Reges"; String s2 = "Marty Stepp"; System.out.println(s1.length()); // 12 System.out.println(s1.indexOf("e")); // 8 System.out.println(s1.substring(7, 10)); // "Reg" String s3 = s2.substring(1, 7); System.out.println(s3.toLowerCase()); // "arty s" Given the following string: // index 0123456789012345678901 String book = "Building Java Programs"; How would you extract the word "Java"? NOTE: End is 13, not 12! 24
Modifying strings (p. 166) Methods like substring and tolowercase build and return a new string, rather than modifying the current string. String s = "lil bow wow"; s.touppercase(); System.out.println(s); // lil bow wow To modify a variable's value, you must reassign it: String s = "lil bow wow"; s = s.touppercase(); System.out.println(s); // LIL BOW WOW 25
Modifying strings (p. 166) String Methods 26
Interactive Programs with Scanner (pp. 166-171) We have been using System.out.println() and System.out.print() to provide output to the console Java also has a System.in.read() to read a character from the console System.in.read() has the following characteristics: It only reads one character It returns the integer Unicode value of the character As a result, System.in.read() is not a very useful 27
Example of System.in.read() Not in text 28
Input and System.in interactive program: Reads input from the console. While the program runs, it asks the user to type input. The input typed by the user is stored in variables in the code. Stores Unicode value of character typed Can be tricky; users are unpredictable and misbehave. But interactive programs have more interesting behavior. Scanner: An object that can read input from many sources. Communicates with System.in (the opposite of System.out) Can also read from files (Ch. 6), web sites, databases,... 29
Scanner syntax (pp. 166-169) The Scanner class is found in the java.util package. import java.util.*; // so you can use Scanner Constructing a Scanner object to read console input: Scanner name = new Scanner(System.in); Example: Scanner console = new Scanner(System.in); 30
Scanner methods (pp. 167) Method nextint() nextdouble() next() nextline() Description reads an int from the user and returns it reads a double from the user reads a one-word String from the user reads a one-line String from the user Each method waits until the user presses Enter. The value typed by the user is returned. System.out.print("How old are you? "); // prompt int age = console.nextint(); System.out.println("You typed " + age); prompt: A message telling the user what input to type. 31
Scanner example 1 (pp. 169-171) import java.util.*; // so that I can use Scanner public class UserInputExample { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("How old are you? "); int age = console.nextint(); age 29 years 36 } } int years = 65 - age; System.out.println(years + " years to retirement!"); Console (user input underlined): How old are you? 29 36 years until retirement! 32
Scanner example 2 (pp. 169-171) import java.util.*; // so that I can use Scanner public class ScannerMultiply { public static void main(string[] args) { Scanner console = new Scanner(System.in); } } System.out.print("Please type two numbers: "); int num1 = console.nextint(); int num2 = console.nextint(); int product = num1 * num2; System.out.println("The product is " + product); Output (user input underlined): Please type two numbers: The product is 48 8 6 The Scanner can read multiple values from one line. Create console as a new scanner object with input from System.in Get first number Get second number Prompt user to enter two numbers User types the two numbers separated by a space (white space) Calculate and print the result 33
Input tokens (p. 168) token: A unit of user input, as read by the Scanner. Tokens are separated by whitespace (spaces, tabs, new lines). How many tokens appear on the following line of input? 23 John Smith 42.0 "Hello world" $2.50 " 19" 1 2 3 4 5 6 7 8 9 34
Input tokens (p. 168) 23 John Smith 42.0 "Hello world" $2.50 " 19" 1 2 3 4 5 6 7 8 9 35
Input tokens (p. 168) When a token is not the type you ask for, it crashes. System.out.print("What is your age? "); int age = console.nextint(); Output: What is your age? Timmy java.util.inputmismatchexception at java.util.scanner.next(unknown Source) at java.util.scanner.nextint(unknown Source)... 36
Scanner Methods (pp. 168-171) Scanner's next method reads a word of input as a String. Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); name = name.touppercase(); System.out.println(name + " has " + name.length() + " letters and starts with " + name.substring(0, 1)); Output: What is your name? Chamillionaire CHAMILLIONAIRE has 14 letters and starts with C The nextline method reads a line of input as a String. System.out.print("What is your address? "); String address = console.nextline(); 37
Use of console.next() (p. 168-171) 23 John Smith 42.0 "Hello world" $2.50 " 19" 38
Use of console.nextline() (p. 168-171) 23 John Smith 42.0 "Hello world" $2.50 " 19" 39
Strings question (pp. 168-171) Write a program that outputs a person's "gangsta name." first initial Diddy last name (all caps) first name -izzle Example Output: Type your name, playa: Marge Simpson Your gangsta name is "M. Diddy SIMPSON Marge-izzle" 40
// This program prints your "gangsta" name. import java.util.*; public class GangstaName { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("Type your name, playa: "); String name = console.nextline(); // split name into first/last name and initials String first = name.substring(0, name.indexof(" ")); String last = name.substring(name.indexof(" ") + 1); last = last.touppercase(); String finitial = first.substring(0, 1); System.out.println("Your gangsta name is \"" + finitial + ". Diddy " + last + " " + first + "-izzle\""); } } 41
NOTE: substring(index) with a single index grabs the substring starting at index through the end of the string. substring(index) is the same as substring(index, name.length()) 42
Assignments for this week 1. Laboratory for Chapter 3 due (Monday 10/6) IMPORTANT: When you email me your laboratory Word Document, be sure it is all in one file 2. Read Section 3.4 for Wednesday (pp. 172-180) 3. Be sure to complete Quiz 9 before leaving class tonight This is another program to write You must demonstrate the program to me before you leave lab 43