Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Starting Out with Java: From Control Structures through Objects 5th edition By Tony Gaddis Source Code: Chapter 9 Code Listing 9-1 (CharacterTest.java) 1 3 4 5 6 7 8 9 import javax.swing.JOptionPane; /** This program demonstrates some of the Character class's character testing methods. */ public class CharacterTest { 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 14 17 input = JOptionPane.showInputDialog("Enter " + 18 "any single character."); 19 ch = input.charAt(0); 20 21 // Test the character. 22 if ( Character.isLetter(ch) ) 23 { 24 25 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 JOptionPane.showMessageDialog(null, "That is a letter."); } if (Character.isDigit(ch)) { JOptionPane.showMessageDialog(null, "That is a digit."); } if ( Character.isLowerCase(ch) ) { JOptionPane.showMessageDialog(null, "That is a lowercase letter."); } if ( Character.isUpperCase(ch) ) { JOptionPane.showMessageDialog(null, "That is an uppercase letter."); } 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 } if ( Character.isSpaceChar(ch) ) { JOptionPane.showMessageDialog(null, "That is a space."); } if ( Character.isWhitespace(ch) ) { JOptionPane.showMessageDialog(null, "That is a whitespace character."); } System.exit(0); } Code Listing 9-2 (CustomerNumber.java) 1 2 3 4 5 import javax.swing.JOptionPane; /** This program tests a customer number to 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 13 14 // Get a customer number. 15 input = JOptionPane.showInputDialog("Enter " + 16 "a customer number in the form LLLNNNN\n" + 17 "(LLL = letters and NNNN = numbers)"); 18 19 20 if ( isValid(input) ) 21 22 23 { JOptionPane.showMessageDialog(null, "That's a valid customer number."); 24 } 25 26 27 else { JOptionPane.showMessageDialog(null, 28 "That is not the proper format of a " + 29 "customer number.\nHere is an " + 30 "example: ABC1234"); 31 } 32 33 System.exit(0); 34 } 35 36 /** 37 The isValid method determines whether a 38 String is a valid customer number. If so, it 39 returns true. 40 @param custNumber The String to test. 41 @return true if valid, otherwise false. 42 */ 43 44 45 46 private static boolean isValid(String custNumber) { boolean goodSoFar = true; (Continued) 47 48 50 51 52 int i = 0; 54 55 56 57 58 59 60 62 63 64 65 66 67 68 69 70 71 } while (goodSoFar && i < 3) if (custNumber.length() != 7) goodSoFar = false; { if (!Character.isLetter(custNumber.charAt(i) )) goodSoFar = false; i++; } while (goodSoFar && i < 7) // What is “I’s” value ? { if (!Character.isDigit(custNumber.charAt(i) )) goodSoFar = false; i++; } return goodSoFar; } Code Listing 9-3 (CircleArea.java) 1 2 3 4 import java.util.Scanner; 5 6 7 class's */ 8 9 public class CircleArea 10 11 12 13 14 15 16 17 18 19 20 21 /** This program demonstrates the Character toUpperCase method. { public static void main(String[] args) { double radius; // The circle's radius double area; // The circle's area String input; // To hold a line of input Char choice; // To hold a single character Scanner keyboard = new Scanner(System.in); do { 22 // Get the circle's radius. 23 System.out.print("Enter the circle's radius: "); (Continued) 24 25 26 27 28 29 radius = keyboard.nextDouble(); // Consume the remaining newline character. keyboard.nextLine(); // Calculate and display the area. area = Math.PI * radius * radius; 30 31 System.out.printf("The area is %.2f.\n", area); 32 33 // 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); 38 39 } while (Character.toUpperCase(choice) 40 } 41 } Program Output with Example Input Shown in Bold Enter the circle's radius: 10 [Enter] The area is 314.16. Do you want to do this again? (Y or N) y [Enter] Enter the circle's radius: 15 [Enter] The area is 706.86. Do you want to do this again? (Y or N) n [Enter] == 'Y'); Code Listing 9-4 (PersonSearch.java) 1 2 3 import java.util.Scanner; 4 5 6 7 This program uses the startsWith method to search using a partial string. */ 8 9 public class PersonSearch 10 11 /** { public static void { main(String[] args) 12 13 14 String lookUp; 15 16 17 18 19 20 21 22 23 String[ ] people = { "Cutshaw, Will", "Davis, George", // To hold a lookup string "Davis, Jenny", "Russert, Phil", "Russell, Cindy", "Setzer, Charles", "Smathers, Holly", "Smith, Chris", "Smith, Brad", "Williams, Jean" }; Scanner keyboard = new Scanner(System.in); (Continued) 25 26 27 28 29 30 System.out.print("Enter the first few characters of " + "the last name to look up: "); lookUp = keyboard.nextLine(); 31 System.out.println("Here are the names that match:"); 32 33 for (String person : people) 34 // Display all of the names that begin with the // string entered by the user. { if ( person.startsWith(lookUp) ) System.out.println(person); 35 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 2 3 4 5 6 7 8 9 import javax.swing.JOptionPane; /** This program displays the number of letters, digits, and whitespace characters in a string. */ public class StringAnalyzer { 10 11 12 13 14 15 16 17 18 public static void main(String [] args) { String input; // To hold input char[] array; // Array for input int letters = 0; // Number of letters int digits = 0; // Number of digits int whitespaces = 0; // Number of whitespaces 19 20 21 22 input = JOptionPane.showInputDialog("Enter " + // Convert the string to a char array. 23 array = input.toCharArray(); // Get a string from the user. "a string:"); 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 } 46 } // Analyze the characters. for (int i = 0; i < array.length; i++) { if ( Character.isLetter( array[i] ) ) letters++; else if ( Character.isDigit( array[i] ) ) digits++; else if ( Character.isWhitespace( array[i] ) ) whitespaces++; } JOptionPane.showMessageDialog(null, "That string contains " + letters + " letters, " + digits + " digits, and " + whitespaces + " whitespace characters."); System.exit(0); Code Listing 9-6 (Telephone.java) 1 2 3 4 5 6 /** The Telephone class provides static methods for formatting and unformatting U.S. telephone numbers. */ 7 public 8 { 9 10 class Telephone 11 public final static int FORMATTED_LENGTH = 13; 12 13 14 15 16 17 public final static int UNFORMATTED_LENGTH = 10; 18 19 20 21 22 23 24 /** The isFormatted method determines whether a string is properly formatted as a U.S. telephone number in the following manner: (XXX)XXX-XXXX @param str The string to test. @return true if the string is properly formatted, or false otherwise. */ public static boolean isFormatted( String str ) 25 { 26 boolean valid; 27 28 // Determine if (str.length() == FORMATTED_LENGTH && str.charAt(0) == '(' && str.charAt(4) == ')' && str.charAt(8) == '-') 29 30 31 32 valid = true; 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 whether str is properly formatted. else valid = false; // Return the value of the valid flag. return valid; } /** The unformat method accepts a string containing a telephone number formatted as: (XXX)XXX-XXXX. If the argument is formatted in this way, the method returns an unformatted string where the parentheses and hyphen have been removed. Otherwise, 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 it returns the original argument. @param str The string to unformat. @return An unformatted string. */ public static String unformat( String { str ) // Create a StringBuilder initialized with str. StringBuilder strb = new StringBuilder(str); Why? if ( isFormatted(str) ) { // First, delete the left paren at position 0. 63 64 65 66 67 strb.deleteCharAt(0); 68 69 70 strb.deleteCharAt(3); // Next, delete the right paren. Because of the // previous deletion it is now located at // position 3. // Next, delete the hyphen. Because of the (Continued) 71 72 // previous deletions it is now located at // position 6. 73 74 75 76 strb.deleteCharAt(6); 77 78 79 80 } // Return the unformatted string. return strb.toString(); } /** The format method formats a string as: (XXX)XXX-XXXX. 81 82 83 84 85 86 87 88 89 90 91 92 93 If the length of the argument is UNFORMATTED_LENGTH the method returns the formatted string. Otherwise, it returns the original argument. @param str The string to format. @return A string formatted as a U.S. telephone number. */ public static String format( String str ) { // Create a StringBuilder initialized with str. StringBuilder strb = new StringBuilder(str); (Continued) 94 95 // If the argument is the correct length, then 96 // format it. 97 98 99 if (str.length() == UNFORMATTED_LENGTH) { // First, insert the left paren at position 0. 100 101 102 strb.insert(0, "("); 103 104 105 strb.insert(4, ")"); 106 107 108 109 strb.insert(8, "-"); 110 111 } 112 } // Next, insert the right paren at position 4. // Next, insert the hyphen at position 8. } // Return the formatted string. return strb.toString(); Code Listing 9-7 (TelephoneTester.java) 1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 import java.util.Scanner; /** This program demonstrates the Telephone class's static methods. */ public class TelephoneTester { public static void main(String[] args) { String phoneNumber; // To hold a phone number Scanner keyboard = new Scanner(System.in); 17 18 19 20 // Get an unformatted telephone number. 21 22 // Format the telephone number. 23 Telephone.format(phoneNumber)); System.out.print("Enter an unformatted telephone number: "); phoneNumber = keyboard.nextLine(); System.out.println("Formatted: " + (Continued) 24 25 26 27 28 29 30 31 32 33 } 34 } // Get a formatted telephone number. System.out.println("Enter a telephone number formatted as"); System.out.print("(XXX)XXX-XXXX : "); phoneNumber = keyboard.nextLine(); // Unformat the telephone number. System.out.println("Unformatted: " + Telephone.unformat(phoneNumber)); Program Output with Example Input Shown in Bold Enter an unformatted telephone number: 9195551212 [Enter] Formatted: (919)555-1212 Enter a telephone number formatted as (XXX)XXX-XXXX : (828)555-1212 [Enter] Unformatted: 8285551212 Code Listing 9-8 (DateComponent.java) 1 2 3 4 5 import java.util.StringTokenizer; /** The DateComponent class extracts the month, 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; 12 13 14 15 private String year; 21 22 23 // To hold the year /** The constructor accepts a String containing a date in the form MONTH/DAY/YEAR. It extracts the month, day, and year from the string. See table 9-11(Overloaded constr) 16 17 18 19 20 // To hold the day @param dateStr A String containing a date. */ public DateComponent( String dateStr ) { // Create a StringTokenizer object. (Continued) StringTokenizer strTokenizer = new StringTokenizer( dateStr, "/“ ); 24 26 27 // Extract the tokens. month = strTokenizer.nextToken(); day = strTokenizer.nextToken(); year = strTokenizer.nextToken(); 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 } /** getMonth method @return The month field. */ public String getMonth() { return month; } /** getDay method @return The day field. */ (Continued) 47 48 49 50 51 52 53 54 55 56 57 public String getDay() { return day; } /** getYear method @return The year field. */ 58 public String getYear() 59 { 60 return year; 61 } 62 } Code Listing 9-9 (DateTester.java) 1 2 3 4 5 6 7 8 /** This program demonstrates the DateComponent class. */ public class DateTester { public static void { main(String[] args) 9 String date = "10/23/2013"; 10 DateComponent dc = 11 12 13 14 15 16 17 18 19 20 21 } 22 } new DateComponent(date); //Create a DateCompenent // Object. System.out.println("Here's the date: " + date); System.out.println("The month is " + dc.getMonth()); System.out.println("The day is " + dc.getDay()); System.out.println("The year is " + dc.getYear()); (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 2 3 4 5 6 7 import java.io.*; import java.util.Scanner; /** The TestScoreReader class reads test scores as tokens from a file and calculates the average of each line of scores. 8 */ 9 10 public class TestScoreReader 11 { 12 private Scanner 13 14 15 16 17 18 19 20 private String inputFile; line; /** The constructor opens a file to read the grades from. @param filename The file to open. */ 21 public TestScoreReader(String filename) throws IOException 22 23 { (Continued) File file = new File(filename); inputFile = new Scanner(file); 24 25 // Why? 26 27 28 29 30 31 32 33 34 } 35 36 37 38 39 public boolean readNextLine() throws IOException { boolean lineRead; // Flag variable-Return Value /** The readNextLine method reads the next line from the file. @return true if the line was read, false otherwise. */ 40 41 42 lineRead = inputFile.hasNext(); 43 if (lineRead) 44 45 46 line = inputFile.nextLine(); // Why?- Returns? // What is “line” ? return lineRead; (Continued) 47 48 49 50 51 52 53 54 } 55 56 57 public double getAverage() { int total = 0; // Accumulator /** The getAverage method calculates the average of the last set of test scores read from the file. @return The average. */ 58 59 double average; // The average test score 60 // Tokenize the last line read from the file. 61 String[ ] tokens = line.split(","); 62 63 // Calculate the total of the test scores. 64 65 66 67 68 69 for (String str : tokens) { total += Integer.parseInt(str); } // Calculate the average of the scores. (Continued) 70 71 72 73 average = (double) total / tokens.length; 74 75 76 77 78 79 80 return average; 81 82 } /** The close method closes the file. */ public void close() throws { 83 84 } 85 } inputFile.close(); IOException Code Listing 9-11 (TestAverages.java) 1 2 3 4 5 6 import java.io.*; // Needed for IOException /** This program uses the TestScoreReader class to read test scores from a file and get 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 16 17 18 19 20 21 22 23 TestScoreReader scoreReader = new TestScoreReader("Grades.csv"); while ( scoreReader.readNextLine() ) //Continue until? { (Continued) 24 average = scoreReader.getAverage(); 25 26 27 28 29 30 31 // Display the student's average. System.out.println("Average for student " + studentNumber + " is " + average); 32 // Increment the student number. 33 34 35 36 37 studentNumber++; 38 39 } 40 } } scoreReader.close(); System.out.println("No more scores."); Program Output Average Average Average Average Average for student 1 is 86.6 for student 2 is 78.8 for student 3 is 90.4 for student 4 is 72.0 for student 5 is 83.4