1 / 37

Building Java Programs

Building Java Programs. Objects String, Character and Scanner. Built-in Types. Some. The Boolean data type. Useful to control flow and logic in programs. Comparisons. Classes and objects. class : A program entity that represents either: 1. A program / module , or

colegrove
Download Presentation

Building Java Programs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Building Java Programs Objects String, Character and Scanner

  2. Built-in Types Some

  3. The Boolean data type Useful to control flow and logic in programs

  4. Comparisons

  5. 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 DrawingPanel class (type) is a template forcreating many DrawingPanel objects (windows). • Java has 1000s of classes. Later (Ch.8) we will write our own. • object: An entity that combinesdata and behavior. • object-oriented programming (OOP): Programs that perform their behavioras interactions between objects.

  6. Objects • object: An entity that containsdata 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: TypeobjectName = new Type(parameters); • Calling an object's method: objectName.methodName(parameters);

  7. Blueprint analogy 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 iPod blueprint/factory state:current song volume battery life behavior:power on/off change station/song change volume choose random song

  8. Strings • string: An object storing a sequence of text characters. • Unlike most other objects, a Stringis 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 + ")";

  9. Stringobjects • 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);

  10. Indexes Characters of a string are numbered with 0-based indexes: String name = "R. Kelly"; 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)

  11. String methods These methods are called using the dot notation: String gangsta = "Dr. Dre"; System.out.println(gangsta.length()); // 7

  12. String method examples // 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" ?

  13. Modifying strings Methods like substring and toLowerCasebuild 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

  14. More Stringmethods

  15. Command Line arguments • A way to pass values (i.e. data) to the program at the launching time > java UseArgument Fadi Hi, Fadi, How are you?

  16. 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[] argsin the main() method • args is an array that may be used to store certain number of string valuespassed to the program by the user at the launching time. // Program that takes three String arguments and prints them in opposite order. publicclassThreeArgs { publicstaticvoid main(String[] args) { System.out.println("Hi " + args[2] + ", " + args[1] + " and " + args[0] + "."); } } > java ThreeArgsAlice Bob Carol Hi Carol, Bob and Alice.

  17. Converting between Strings and Numbers • Convert from string to number: String str = “23”;int n = Integer.parseInt(str); double x = Double.parseDouble(str); • Convert to string:String str = "" + n; str = Integer.toString(n);

  18. Command line argument- int to String // Compute the average of n random doubles between 0 and 1 // Usage example: java RandomsAverage 100 publicclassRandomsAverage { publicstaticvoid main(String[] args) { int n = Integer.parseInt(args[0]); double sum = 0.0; for (int i = 0; i < n; i++) { sum = sum + Math.random(); } System.out.println(sum / n); } }

  19. command line argument - double to String // Compute the average of n random doubles between a and b // Usage: java Randoms2 n a b (Ex: java Randoms2 100 3.0 9.0) publicclass Randoms2 { publicstaticvoid main(String[] args) { int n = Integer.parseInt(args[0]); double a = Double.parseDouble(args[1]); double b = Double.parseDouble(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); } }

  20. Type Conversions • Two mechanisms: • Automatic • Explicit: either by casting, or by a method call

  21. Type Conversions-Example

  22. Type char • char : A primitive type representing single characters. • A String is stored internally as an array of char String s = "Ali 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

  23. The charAt method • The chars in a String can be accessed using the charAt method. • accepts an int index parameter and returns the char at that index String food = "cookie"; char firstLetter = food.charAt(0); // 'c' System.out.println(firstLetter + " is for " + food); • You can use a for loop to print or examine each character. String major = "CSE"; for (inti = 0; i < major.length(); i++) { char c = major.charAt(i); System.out.println(c); } Output: C S E

  24. Comparing char values • You can compare chars with ==, !=, and other operators: String word = “Hellos”; char last = word.charAt(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); }

  25. The Character Class • boolean isDigit(char) : • Checks whether or not character is '0‘ through '9‘ • Example: Character.isDigit('X') returns false • boolean isLetter(char) • Checks whether or not character is in range 'a' to 'z' or 'A' to 'Z‘ • Example: Character.isLetter('f') returnstrue • boolean isLowerCase(char) • Checks whether or not character is a lowercase letter • Example: Character.isLowerCase('Q') returnsfalse • boolean isUpperCase(char) • Checks whether or not character is an uppercase letter • Example: Character.isUpperCase('Q') returnstrue • char toLowerCase(char) • Checks the lowercase version of the given letter • Example: Character.toLowerCase('Q') returns'q‘ • char toUpperCase(char) • Checks whether the uppercase version of the given letter • Example: Character.toUpperCase('x') returns'X'

  26. char vs. int • Each charis mapped to an integer value internally • Called an ASCII value 'A' is 65 'B' is 66 ' ' is 32 'a' is 97 'b' is 98 '*' is 42 • Mixing char and int causes automatic conversion to int. 'a' + 10 is 107, 'A' + 'A' is 130 • To convert an int into the equivalent char, type-cast it. (char) ('a' + 2) is 'c'

  27. 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.toUpperCase(); // "H" intlen = s.length(); // 1 char first = s.charAt(0); // 'H' A char is primitive; you can't call methods on it. char c = 'h'; c = c.toUpperCase(); // ERROR s = s.charAt(0).toUpperCase(); // ERROR What is s + 1 ? What is c + 1 ? What is s + s ? What is c + c ?

  28. Interactive Programs with Scanner

  29. 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, ...

  30. 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);

  31. Scanner methods • 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.

  32. Scanner example 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(); int years = 65 - age; System.out.println(years + " years to retirement!"); } } • Console (user input underlined): How old are you? 36 years until retirement! 29

  33. Scanner example 2 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: 8 6 The product is 48 • The Scanner can read multiple values from one line.

  34. 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.nextInt(); Output: What is your age? Timmy java.util.InputMismatchException at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) ...

  35. 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(); Strings as user input

  36. 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"

  37. Strings answer // 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\""); } }

More Related