Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 9.

Slides:



Advertisements
Similar presentations
Java Programming Strings Chapter 7.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Introduction to Computer Programming Decisions If/Else Booleans.
1 Tirgul no. 3 Topics covered: H Iteration. H Defining and using classes.
Introduction to Computer Programming Loops N Decisions If/Else Counting Loops.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
TA: Nouf Al-Harbi NoufNaief.net :::
CS 180 Recitation 8 / {30, 31} / Announcements Project 1 is out –Due 10:00pm –Start early! –Use the newsgroup for your questions –LWSN B146.
Computer Programming Lab(4).
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Chapter 9: Text Processing and More about Wrapper Classes Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Starting Out with Java: From Control Structures through Objects
Chapter 6: Iteration Part 2. Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i
One Dimensional Array. Introduction to Arrays Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection.
11 Chapter 5 METHODS CONT’D. 22 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method Objects are passed by reference.
Starting Out with Java: From Control Structures through Objects
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Arrays Pepper. What is an Array A box that holds many of the exact same type in mini-boxes A number points to the mini-box The number starts at 0 String.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Chapter The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number.
Starting Out with Java: From Control Structures through Objects
Chapter 4: Control Structures II
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Methods Chapter Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
COM S 207 Method Instructor: Ying Cai Department of Computer Science Iowa State University
Java 1.5 The New Java Mike Orsega Central Carolina CC.
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
10-2 Chapter 10 discusses the following main topics:  Introduction to Wrapper Classes  Character Testing and Conversion with the Character Class  More.
Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Strings JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 10: Text Processing and More about Wrapper Classes Starting.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
19-Dec-15 Tokenizers. Tokens A tokenizer is a program that extracts tokens from an input stream A token has two parts: Its value—this is just the characters.
Department of Computer Engineering Using Objects Computer Programming for International Engineers.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
8-1 Chapter-7 Part1 Introduction to Arrays –Array Types –Creating/Declaring Arrays –Initializing Arrays –Processing Array Contents –Passing Arrays as Arguments.
Computer Programming1 Computer Science 1 Computer Programming.
Files Review For output to a file: –FileOutputStream variable initialized to filename (String) and append/not append (boolean) –PrintWriter variable initialized.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 5.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING Switch Statement.
C OMMON M ISTAKES CSC Java Program Structure  String Methods.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Programming Fundamentals 2: Libraries/ F II Objectives – –utilize some useful Java libraries e.g. String, Scanner, HashMap, and Random.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
CSC111 Quick Revision.
Arrays, Searching and Sorting
Starting Out with Java: From Control Structures through Objects
Chapter 4: Loops and Files
Introduction to Classes and Methods
Lecture Notes – Week 2 Lecture-2
F II 6. Using Libraries Objectives
Dr. Sampath Jayarathna Cal Poly Pomona
Starting Out with Java: From Control Structures through Objects
Presentation transcript:

Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 9

Code Listing 9-1 (CharacterTest.java) 1 import javax.swing.JOptionPane; 3 /** 4 This program demonstrates some of the Character 5 class's character testing methods. 6 */ 7 8 public class CharacterTest 9 { 10 public static void main(String[] args) 11 { 12 String input; // To hold the user's input 13 char ch; // To hold a single character input = JOptionPane.showInputDialog("Enter " + 18 "any single character."); 19 ch = input.charAt(0); // Test the character. 22 if ( Character.isLetter(ch) ) 23 {

24 JOptionPane.showMessageDialog(null, 25 "That is a letter."); 27 } 28 if (Character.isDigit(ch)) 29 { 30 JOptionPane.showMessageDialog(null, 31 "That is a digit."); 32 } if ( Character.isLowerCase(ch) ) 35 { 36 JOptionPane.showMessageDialog(null, 37 "That is a lowercase letter."); 38 } if ( Character.isUpperCase(ch) ) 41 { 42 JOptionPane.showMessageDialog(null, 43 "That is an uppercase letter."); 44 } 45

46 if ( Character.isSpaceChar(ch) ) 47 { 48 JOptionPane.showMessageDialog(null, 49 "That is a space."); 50 } if ( Character.isWhitespace(ch) ) 53 { 54 JOptionPane.showMessageDialog(null, 55 "That is a whitespace character."); 56 } System.exit(0); 59 } 60 }

Code Listing 9-2 (CustomerNumber.java) 1 import javax.swing.JOptionPane; 2 3 /** 4 This program tests a customer number to 5 verify that it is in the proper format. 6 */ 7 8 public class CustomerNumber 9 { 10 public static void main (String[] args) 11 { 12 String input ; // To hold the user's input // Get a customer number. 15 input = JOptionPane.showInputDialog("Enter " + 16 "a customer number in the form LLLNNNN \n" + 17 "(LLL = letters and NNNN = numbers)"); if ( isValid (input) ) 21 { 22 JOptionPane.showMessageDialog(null, 23 " That's a valid customer number.");

24 } 25 else 26 { 27 JOptionPane.showMessageDialog(null, 28 " That is not the proper format of a " + 29 "customer number.\nHere is an " + 30 "example: ABC1234"); 31 } System.exit(0); 34} /** 37 The isValid method determines whether a 38 String is a valid customer number. If so, it 39 returns true. custNumber The String to test. true if valid, otherwise false. 42 */ private static boolean isValid ( String custNumber) 45 { 46 boolean goodSoFar = true ; (Continued)

47 int i = 0; if ( custNumber.length() ! = 7 ) 51 goodSoFar = false ; while ( goodSoFar && i < 3 ) 55 { 56 if ( ! Character.isLetter(custNumber.charAt(i) )) 57 goodSoFar = false; 58 i++; 59 } while ( goodSoFar && i < 7 ) // What is “I’s” value ? 63 { 64 if ( ! Character.isDigit(custNumber.charAt(i) )) 65 goodSoFar = false; 66 i++; 67 } return goodSoFar; 70 } 71 }

Code Listing 9-3 (CircleArea.java) 1 import java.util.Scanner; 2 3 /** 4 This program demonstrates the Character 5 class's toUpperCase method. 6 */ 7 8 public class CircleArea 9 { 10 public static void main (String[] args) 11 { 12 double radius; // The circle's radius 13 double area; // The circle's area 14 String input; // To hold a line of input 15 Char choice; // To hold a single character Scanner keyboard = new Scanner(System.in); do 21 { 22 // Get the circle's radius. 23 System.out.print(" Enter the circle's radius : "); (Continued)

24 radius = keyboard.nextDouble(); // Consume the remaining newline character. 27 keyboard.nextLine(); // Calculate and display the area. 30 area = Math.PI * radius * radius; 31 System.out.printf("The area is %.2f.\n", area); // Repeat this? 34 System.out.print("Do you want to do this " + 35 "again? (Y or N) "); 36 input = keyboard.nextLine(); 37 choice = input. charAt (0); } while (Character.toUpperCase(choice) == 'Y'); 40 } 41 } Program Output with Example Input Shown in Bold Enter the circle's radius: 10 [Enter] The area is Do you want to do this again? (Y or N) y [Enter] Enter the circle's radius: 15 [Enter] The area is Do you want to do this again? (Y or N) n [Enter]

Code Listing 9-4 (PersonSearch.java) 1 import java.util.Scanner; 2 3 /** 4 This program uses the startsWith method to search using 5 a partial string. 6 */ 7 8 public class PersonSearch 9 { 10 public static void main (String[] args) 11 { 12 String lookUp; // To hold a lookup string String[ ] people = { "Cutshaw, Will", "Davis, George", 16 "Davis, Jenny", "Russert, Phil", 17 "Russell, Cindy", "Setzer, Charles", 18 "Smathers, Holly", "Smith, Chris", 19 "Smith, Brad", "Williams, Jean" }; Scanner keyboard = new Scanner(System.in); 23 (Continued)

25 System.out.print("Enter the first few characters of " + 26 "the last name to look up: "); 27 lookUp = keyboard.nextLine(); // Display all of the names that begin with the 30 // string entered by the user. 31 System.out.println(" Here are the names that match :"); 32 for (String person : people) 33 { 34 if ( person.startsWith(lookUp) ) 35 System.out.println( person ); 36 } 37 } 38 } Program Output with Example Input Shown in Bold Enter the first few characters of the last name to look up: Davis [Enter] Here are the names that match: Davis, George Davis, Jenny Program Output with Example Input Shown in Bold Enter the first few characters of the last name to look up: Russ [Enter] Here are the names that match: Russert, Phil Russell, Cindy

Code Listing 9-5 (StringAnalyzer.java) 1 import javax.swing.JOptionPane; 2 3 /** 4 This program displays the number of letters, 5 digits, and whitespace characters in a string. 6 */ 7 8 public class StringAnalyzer 9 { 10 public static void main (String [] args) 11 { 12 String input; // To hold input 13 char[] array; // Array for input 14 int letters = 0; // Number of letters 15 int digits = 0; // Number of digits 16 int whitespaces = 0; // Number of whitespaces // Get a string from the user. 19 input = JOptionPane.showInputDialog("Enter " + 20 "a string:"); // Convert the string to a char array. 23 array = input. toCharArray(); (Continued)

24 25 // Analyze the characters. 26 for (int i = 0; i < array.length; i++) 27 { 28 if ( Character.isLetter ( array[i] ) ) 29 letters++; 30 else if ( Character.isDigit ( array[i] ) ) 31 digits++; 32 else if ( Character.isWhitespace ( array[i] ) ) 33 whitespaces++; 34 } JOptionPane.showMessageDialog(null, 38 " That string contains " + 39 letters + " letters, " + 40 digits + " digits, and " + 41 whitespaces + 42 " whitespace characters."); System.exit(0); 45 } 46 }

Code Listing 9-6 (Telephone.java) 1 /** 2 The Telephone class provides static methods 3 for formatting and unformatting U.S. telephone 4 numbers. 5 */ 6 7 public class Telephone 8{ public final static int FORMATTED_LENGTH = 13; 12 public final static int UNFORMATTED_LENGTH = 10; /** 15The isFormatted method determines whether a 16 string is properly formatted as a U.S. telephone 17 number in the following manner: 18 ( XXX ) XXX - XXXX str The string to test. true if the string is properly formatted, 21 or false otherwise. 22 */ public static boolean isFormatted( String str ) (Continued)

25 { 26 boolean valid ; // Determine whether str is properly formatted. 29 if ( str.length() == FORMATTED_LENGTH && 30 str.charAt(0) == ' ( ' && 31 str.charAt(4) == ' ) ' && 32 str.charAt(8) == ' -' ) 33 valid = true; 34 else 35 valid = false; // Return the value of the valid flag. 38 return valid ; 39 } /** 42 The unformat method accepts a string containing 43 a telephone number formatted as: 44 (XXX)XXX-XXXX. 45 If the argument is formatted in this way, the 46 method returns an unformatted string where the 47 parentheses and hyphen have been removed. Otherwise,

48 it returns the original argument. str The string to unformat. An unformatted string. 51 */ public static String unformat ( String str ) 54 { 55 // Create a StringBuilder initialized with str. Why? 56 StringBuilder strb = new StringBuilder ( str ); if ( isFormatted(str) ) 61 { 62 // First, delete the left paren at position strb.deleteCharAt(0); // Next, delete the right paren. Because of the 66 // previous deletion it is now located at 67 // position strb.deleteCharAt(3); // Next, delete the hyphen. Because of the (Continued)

71 // previous deletions it is now located at 72 // position strb.deleteCharAt(6); 74 } // Return the unformatted string. 77 return strb.toString(); 78 } /** 81 The format method formats a string as: 82 (XXX)XXX - XXXX. 83 If the length of the argument is UNFORMATTED_LENGTH 84 the method returns the formatted string. Otherwise, 85 it returns the original argument. str The string to format. A string formatted as a U.S. telephone number. 88 */ public static String format ( String str ) 91 { 92 // Create a StringBuilder initialized with str. 93 StringBuilder strb = new StringBuilder(str); (Continued)

94 95 // If the argument is the correct length, then 96 // format it. 97 if ( str.length() == UNFORMATTED_LENGTH) 98 { 99 // First, insert the left paren at position strb.insert(0, "("); // Next, insert the right paren at position strb.insert(4, ")"); // Next, insert the hyphen at position strb.insert(8, "-"); 107 } // Return the formatted string. 110 return strb. toString(); 111 } 112 }

Code Listing 9-7 (TelephoneTester.java) 1 import java.util.Scanner; 2 3 /** 4 This program demonstrates the Telephone 5 class's static methods. 6 */ 7 8 public class TelephoneTester 9 { 10 public static void main (String[] args) 11 { 12 String phoneNumber ; // To hold a phone number Scanner keyboard = new Scanner(System.in); // Get an unformatted telephone number. 18 System.out.print("Enter an unformatted telephone number: "); 19 phoneNumber = keyboard.nextLine(); // Format the telephone number. 22 System.out.println("Formatted: " + 23 Telephone. format(phoneNumber) ); (Continued)

24 25 // Get a formatted telephone number. 26 System.out.println("Enter a telephone number formatted as"); 27 System.out.print("(XXX)XXX-XXXX : "); 28 phoneNumber = keyboard.nextLine(); // Unformat the telephone number. 31 System.out.println("Unformatted: " + 32 Telephone. unformat(phoneNumber)) ; 33 } 34} Program Output with Example Input Shown in Bold Enter an unformatted telephone number: [Enter] Formatted: (919) Enter a telephone number formatted as (XXX)XXX-XXXX : (828) [Enter] Unformatted:

Code Listing 9-8 (DateComponent.java) 1 import java.util.StringTokenizer; 2 3 /** 4 The DateComponent class extracts the month, 5 day, and year from a string containing a date. 6 */ 7 8 public class DateComponent 9 { 10 private String month; // To hold the month 11 private String day; // To hold the day 12 private String year; // To hold the year /** 15 The constructor accepts a String containing a date 16 in the form MONTH/DAY/YEAR. It extracts the month, 17 day, and year from the string. See table 9-11(Overloaded constr) dateStr A String containing a date. 19 */ public DateComponent ( String dateStr ) 22 { 23 // Create a StringTokenizer object. (Continued)

24 StringTokenizer strTokenizer = new StringTokenizer( dateStr, "/“ ); // Extract the tokens. 28 month = strTokenizer.nextToken(); 29 day = strTokenizer.nextToken(); 30 year = strTokenizer.nextToken(); 31 } /** 34 getMonth method The month field. 36 */ public String getMonth() 39 { 40 return month; 41 } /** 44 getDay method The day field. 46 */ (Continued)

47 48 public String getDay() 49 { 50 return day; 51 } /** 54 getYear method The year field. 56 */ public String getYear() 59 { 60 return year; 61 } 62 }

Code Listing 9-9 (DateTester.java) 1 /** 2 This program demonstrates the DateComponent class. 3 */ 4 5 public class DateTester 6 { 7 public static void main (String[] args) 8 { 9 String date = "10/23/2013"; 10 DateComponent dc = 11 new DateComponent ( date ) ; //Create a DateCompenent 12 // Object. 13 System.out.println("Here's the date: " + 14 date); 15 System.out.println("The month is " + 16 dc. getMonth()); 17 System.out.println("The day is " + 18 dc. getDay()); 19 System.out.println("The year is " + 20 dc. getYear()); 21 } 22 } (Continued)

Program Output Here's the date: 10/23/2013 The month is 10 The day is 23 The year is 2013

Code Listing 9-10 (TestScoreReader.java) 1 import java.io.*; 2 import java.util.Scanner; 3 4 /** 5 The TestScoreReader class reads test scores as 6 tokens from a file and calculates the average 7 of each line of scores. 8 */ 9 10 public class TestScoreReader 11 { 12 private Scanner inputFile; 13 private String line; /** 16 The constructor opens a file to read 17 the grades from. filename The file to open. 19 */ public TestScoreReader(String filename) 22 throws IOException 23 { (Continued)

24 File file = new File(filename); 25 inputFile = new Scanner(file); // Why? 26 } /** 29 The readNextLine method reads the next line 30 from the file. true if the line was read, false 32 otherwise. 33 */ public boolean readNextLine() throws IOException 36 { 37 boolean lineRead ; // Flag variable-Return Value lineRead = inputFile.hasNext(); // Why?- Returns? if ( lineRead ) 44 line = inputFile.nextLine(); // What is “line” ? return lineRead; (Continued)

47 } /** 50 The getAverage method calculates the average 51 of the last set of test scores read from the file. The average. 53 */ public double getAverage() 56 { 57 int total = 0; // Accumulator 58 double average; // The average test score // Tokenize the last line read from the file. 61 String[ ] tokens = line. split(", "); // Calculate the total of the test scores. 64 for (String str : tokens) 65 { 66 total += Integer.parseInt(str); 67 } // Calculate the average of the scores. (Continued)

70 71 average = (double) total / tokens.length; return average; 75 } /** 78 The close method closes the file. 79 */ public void close() throws IOException 82 { 83 inputFile.close(); 84 } 85 }

Code Listing 9-11 (TestAverages.java) 1 import java.io.*; // Needed for IOException 2 3 /** 4 This program uses the TestScoreReader class 5 to read test scores from a file and get 6 their averages. 7 */ 8 9 public class TestAverages 10 { 11 public static void main (String[] args) 12 throws IOException 13 { 14 double average; // Test average 15 int studentNumber = 1; // Control variable TestScoreReader scoreReader = 19 new TestScoreReader("Grades.csv"); while ( scoreReader.readNextLine() ) //Continue until? 23 { (Continued)

24 25 average = scoreReader. getAverage(); // Display the student's average. 28 System.out.println("Average for student " + 29 studentNumber + " is " + 30 average); // Increment the student number. 33 studentNumber++; 34 } scoreReader.close(); 38 System.out.println(" No more scores."); 39 } 40 } Program Output Average for student 1 is 86.6 Average for student 2 is 78.8 Average for student 3 is 90.4 Average for student 4 is 72.0 Average for student 5 is 83.4 No more scores.