Building Java Programs Objects String Character and Scanner
Building Java Programs Objects String, Character and Scanner
Built-in Types Some 2
The Boolean data type Useful to control flow and logic in programs 3
Comparisons 4
Classes and objects • class: A program entity that represents either: 1. A program / module, or 2. A type of objects. – A class is a blueprint or template for constructing objects. – Example: The Drawing. Panel class (type) is a template for creating many Drawing. Panel objects (windows). • Java has 1000 s 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. 5
Objects • object: An entity that contains data and behavior. – data: variables inside the object – behavior: methods inside the object • You interact with the methods; the data is hidden in the object. • Constructing (creating) an object: Type object. Name = new Type(parameters); • Calling an object's method: object. Name. method. Name(parameters); 6
Blueprint analogy i. Pod blueprint/factory state: current song volume battery life behavior: power on/off change station/song change volume choose random song creates i. Pod #1 i. Pod #2 i. Pod #3 state: song = "1, 000 Miles" volume = 17 battery life = 2. 5 hrs state: song = "Letting You" volume = 9 battery life = 3. 41 hrs state: song = "Discipline" volume = 24 battery life = 1. 8 hrs behavior: power on/off change station/song change volume choose random song 7
Strings • 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; – Examples: String name = "Marla Singer"; int x = 3; int y = 5; String point = "(" + x + ", " + y + ")"; 8
String objects § A variable of type String is different from the other (primitive) data types we’ve seen so far § It is actually a reference to a String object. § The methods that operate on these types are invoked differently. § Examples: String str = "hello there!"; int len = str. length(); // note where str is String first = str. substring(0, 1); 9
Indexes • Characters of a string are numbered with 0 -based indexes: String name = "R. Kelly"; index 0 1 character R . 2 3 4 5 6 7 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) 10
String methods Method name index. Of(str) Description index where the start of the given string appears in this string (-1 if not found) length() number of characters in this string substring(index 1, index 2) or substring(index 1) the characters in this string from index 1 (inclusive) to index 2 (exclusive); if index 2 is omitted, grabs till end of string to. Lower. Case() a new string with all lowercase letters to. Upper. Case() 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 11
String method examples // index 012345678901 String s 1 = "Stuart Reges"; String s 2 = "Marty Stepp"; System. out. println(s 1. length()); System. out. println(s 1. index. Of("e")); // 12 // 8 System. out. println(s 1. substring(7, 10)); // "Reg" String s 3 = s 2. substring(1, 7); System. out. println(s 3. to. Lower. Case()); // "arty s" • Given the following string: // index 012345678901 String book = "Building Java Programs"; – How would you extract the word "Java" ? 12
Modifying strings • Methods like substring and to. Lower. Case build and return a new string, rather than modifying the current string. String s = "lil bow wow"; s. to. Upper. Case(); System. out. println(s); // lil bow wow • To modify a variable's value, you must reassign it: String s = "lil bow wow"; s = s. to. Upper. Case(); System. out. println(s); // LIL BOW WOW 13
More String methods 14
Command Line arguments • A way to pass values (i. e. data) to the program at the launching time > java Use. Argument Fadi Hi, Fadi, How are you? 15
Arrays (to be revisited) • array: object that stores many values of the same type. – element: One value in an array. – index: A 0 -based integer to access an element from an array. • String[] args in the main() method – args is an array that may be used to store certain number of string values passed to the program by the user at the launching time. // Program that takes three String arguments and prints them in opposite order. public class Three. Args { public static void main(String[] args) { System. out. println("Hi " + args[2] + ", " + args[1] + " and " + args[0] + ". "); } } > java Three. Args Alice Bob Carol Hi Carol, Bob and Alice. 16
Converting between Strings and Numbers • Convert from string to number: String str = “ 23”; int n = Integer. parse. Int(str); double x = Double. parse. Double(str); • Convert to string: String str = "" + n; str = Integer. to. String(n); 17
Command line argument- int to String // Compute the average of n random doubles between 0 and 1 // Usage example: java Randoms. Average 100 public class Randoms. Average { public static void main(String[] args) { int n = Integer. parse. Int(args[0]); double sum = 0. 0; for (int i = 0; i < n; i++) { sum = sum + Math. random(); } System. out. println(sum / n); } } 18
command line argument - double to String // Compute the average of n random doubles between a and b // Usage: java Randoms 2 n a b (Ex: java Randoms 2 100 3. 0 9. 0) public class Randoms 2 { public static void main(String[] args) { int n = Integer. parse. Int(args[0]); double a = Double. parse. Double(args[1]); double b = Double. parse. Double(args[2]); double sum = 0. 0; for (int i = 0; i < n; i++) { double r = Math. random(); r = a + r * (b - a); sum = sum + r; } System. out. println(sum / n); } } 19
Type Conversions Two mechanisms: • Automatic • Explicit: either by casting, or by a method call 20
Type Conversions-Example 21
Type char • char : A primitive type representing single characters. – A String is stored internally as an array of char String s = "Ali G. "; index 0 1 2 3 4 5 value 'A' 'l' 'i' ' ' 'G' '. ' – It is legal to have variables, parameters, returns of type char • surrounded with apostrophes: 'a' or '4' or 'n' or ''' char letter = 'P'; System. out. println(letter); // P System. out. println(letter + " Diddy"); // P Diddy 22
The char. At method • The chars in a String can be accessed using the char. At method. – accepts an int index parameter and returns the char at that index String food = "cookie"; char first. Letter = food. char. At(0); // 'c' System. out. println(first. Letter + " is for " + food); • You can use a for loop to print or examine each character. String major = "CSE"; for (int i = 0; i < major. length(); i++) { char c = major. char. At(i); System. out. println(c); } Output: C S E 23
Comparing char values • You can compare chars with ==, !=, and other operators: String word = “Hellos”; char last = word. char. At(word. length() - 1); boolean test = last == 's'; System. out. println(test); // prints the alphabet for (char c = 'a'; c <= 'z'; c++) { System. out. println(c); } // prints the ASCII code for (char c = 'a'; c <= 'z'; c++) { System. out. println((int)c); } 24
The Character Class boolean is. Digit(char) : • • Checks whether or not character is '0‘ through '9‘ Example: Character. is. Digit('X') returns false boolean is. Letter(char) • • Checks whether or not character is in range 'a' to 'z' or 'A' to 'Z‘ Example: Character. is. Letter('f') returns true boolean is. Lower. Case(char) • • Checks whether or not character is a lowercase letter Example: Character. is. Lower. Case('Q') returns false boolean is. Upper. Case(char) • • Checks whether or not character is an uppercase letter Example: Character. is. Upper. Case('Q') returns true char to. Lower. Case(char) • • Checks the lowercase version of the given letter Example: Character. to. Lower. Case('Q') returns 'q‘ char to. Upper. Case(char) • • Checks whether the uppercase version of the given letter Example: Character. to. Upper. Case('x') returns 'X' 25
char vs. int • Each char is mapped to an integer value internally – Called an ASCII value 'A' is 65 'a' is 97 'B' is 66 'b' is 98 ' ' is 32 '*' is 42 – Mixing char and int causes automatic conversion to int. 'a' + 10 is 107, 'A' + 'A' is 130 – To convert an into the equivalent char, type-cast it. (char) ('a' + 2) is 'c' 26
char vs. String • "h" is a String, but 'h' is a char (they are different) • A String is an object; it contains methods. String s = "h"; s = s. to. Upper. Case(); int len = s. length(); char first = s. char. At(0); // "H" // 1 // 'H' • A char is primitive; you can't call methods on it. char c = 'h'; c = c. to. Upper. Case(); s = s. char. At(0). to. Upper. Case(); – What is s + 1 ? What is c + 1 ? – What is s + s ? What is c + c ? // ERROR 27
Interactive Programs with Scanner
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. – 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 • 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 Method next. Int() Description reads an int from the user and returns it next. Double() reads a double from the user next() reads a one-word String from the user next. Line() 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. next. Int(); System. out. println("You typed " + age); • prompt: A message telling the user what input to type. 31
Scanner example import java. util. *; // so that I can use Scanner public class User. Input. Example { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("How old are you? "); int age = console. next. Int(); 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 import java. util. *; // so that I can use Scanner public class Scanner. Multiply { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Please type two numbers: "); int num 1 = console. next. Int(); int num 2 = console. next. Int(); int product = num 1 * num 2; System. out. println("The product is " + product); } } • Output (user input underlined): Please type two numbers: 8 6 The product is 48 – The Scanner can read multiple values from one line. 33
Input tokens • 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" • When a token is not the type you ask for, it crashes. System. out. print("What is your age? "); int age = console. next. Int(); Output: What is your age? Timmy java. util. Input. Mismatch. Exception at java. util. Scanner. next(Unknown Source) at java. util. Scanner. next. Int(Unknown Source). . . 34
Strings as user input • 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. to. Upper. Case(); 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 next. Line method reads a line of input as a String. System. out. print("What is your address? "); String address = console. next. Line(); 35
Strings question • 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" 36
Strings answer // This program prints your "gangsta" name. import java. util. *; public class Gangsta. Name { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Type your name, playa: "); String name = console. next. Line(); // split name into first/last name and initials String first = name. substring(0, name. index. Of(" ")); String last = name. substring(name. index. Of(" ") + 1); last = last. to. Upper. Case(); String f. Initial = first. substring(0, 1); System. out. println("Your gangsta name is "" + f. Initial + ". Diddy " + last + " " + first + "-izzle""); } } 37
- Slides: 37