840 likes | 1.09k Vues
Starting Out with Java: From Control Structures through Objects 5 th edition By Tony Gaddis Source Code: Chapter 10. Code Listing 10-1 (GradedActivity.java) 1 /** A class that holds a grade for a graded activity. General class that w ill be “extended” later . 3 */ 4
E N D
Starting Out with Java:From Control Structures through Objects 5th edition By Tony Gaddis Source Code: Chapter 10
Code Listing 10-1 (GradedActivity.java) 1 /** A class that holds a grade for a graded activity. General class that will be “extended” later. 3 */ 4 5 public class GradedActivity 6 { 7 private double score; // Numeric score- Data Field 8 9 /** 10 The setScore method sets the score field. 11 @param s The value to store in score. 12 */ 13 14 public void setScore( doubles) // Note: NO CONSTRUCTOR Explicit. 15 { 16 score = s; 17 } 18 19 /** 20 The getScore method returns the score. 21 @return The value stored in the score field. 22 */ (Continued)
23 24 public double getScore() 25 { 26 return score; 27 } 28 29 /** 30 The getGrade method returns a letter grade 31 determined from the score field. 32 @return The letter grade. 33 */ 34 35 public char getGrade() 36 { 37 char letterGrade; 38 39 if (score >= 90) 40 letterGrade = 'A'; 41 else if (score >= 80) 42 letterGrade = 'B'; 43 else if (score >= 70) 44 letterGrade = 'C'; (Continued)
45 else if (score >= 60) 46 letterGrade = 'D'; 47 else 48 letterGrade = 'F'; 49 50 return letterGrade; 51 } 52 }
Code Listing 10-2 (GradeDemo.java) 1 import javax.swing.JOptionPane; 2 3 /** 4 This program demonstrates the GradedActivity 5 class. Not a sub class. 6 */ 7 8 public class GradeDemo 9 { 10 public static void main(String[] args) 11 { 12 String input; // To hold input 13 double testScore; // A test score 14 // Create a GradedActivity object. 16 GradedActivitygrade = new GradedActivity(); // Invokes What? 17 // Get a test score. 19 Input = JOptionPane.showInputDialog("Enter " + 20 "a numeric test score."); 21 testScore = Double.parseDouble(input); 22 (Continued)
// Store the score in the grade object. 24 grade.setScore(testScore); // Defined where? 25 // Display the letter grade for the score. 27 JOptionPane.showMessageDialog(null, 28 "The grade for that test is " + 29 grade.getGrade()); 30 31 System.exit(0); 32 } 33 }
Code Listing 10-3 (FinalExam.java) 1 /** This class determines the grade for a final exam. A sub class-inherits what? Does not inherit? 3 */ 4 5 public class FinalExamextends GradedActivity 6 { 7 private int numQuestions; // Number of questions 8 private double pointsEach; // Points for each question 9 private int numMissed; // Questions missed 10 11 /** 12 The constructor sets the number of questions on the 13 exam and the number of questions missed. 14 @param questions The number of questions. 15 @param missed The number of questions missed. 16 */ 17 18 public FinalExam( int questions, int missed ) // What is executed FIRST? 19 { 20 double numericScore; // To hold a numeric score 21 22 // Set the numQuestionsand numMissed fields. (Continued)
23 numQuestions= questions; 24 numMissed = missed; 25 26 27 28 pointsEach = 100.0 / questions; 29 numericScore = 100.0 - (missed * pointsEach); // 3 IV’s are set. 30 31 // Call the inherited setScore method to // set the numeric score. 33 setScore( numericScore); // Invokes what? Defined where? Why? 34 } 35 36 /** 37 The getPointsEach method returns the number of 38 points each question is worth. 39 @return The value in the pointsEach field. 40 */ 41 42 public double getPointsEach() // Accessor 43 { 44 return pointsEach; (Continued)
45 } 46 47 /** 48 The getNumMissed method returns the number of 49 questions missed. 50 @return The value in the numMissed field. 51 */ 52 53 public int getNumMissed() // Accessor 54 { 55 return numMissed; 56 } 57 }
Code Listing 10-4 (FinalExamDemo.java) 1 import javax.swing.JOptionPane; 2 3 /** 4 This program demonstrates the FinalExam class, 5 which extends the GradedActivity class. 6 */ 7 8 public class FinalExamDemo 9 { 10 public static void main(String[] args) 11 { 12 String input; // To hold input 13 intquestions; // Number of questions 14 intmissed; // Number of questions missed 15 16 // Get the number of questions on the exam. 17 input = JOptionPane.showInputDialog("How many " + 18 "questions are on the final exam?"); 19 questions = Integer.parseInt(input); 20 21 // Get the number of questions the student missed. 22 input= JOptionPane.showInputDialog("How many " + (Continued)
23 "questions did the student miss?"); 24 missed= Integer.parseInt(input); 25 // Create a FinalExam object. 27 FinalExamexam = new FinalExam(questions, missed); 28 // Display the test results. 30 JOptionPane.showMessageDialog(null, 31 "Each question counts " + exam.getPointsEach()+ // Defined where? 32 " points.\nThe exam score is " + 33 exam.getScore() + "\nThe exam grade is " + // Defined where? 34 exam.getGrade()); 35 36 System.exit(0); 37 } 38 }
Code Listing 10-5 (SuperClass1.java) 1 public class SuperClass1 2 { 3 /** 4 Constructor 5 */ 6 7 public SuperClass1() 8 { 9 System.out.println("This is the " + 10 "superclass constructor."); 11 } 12 }
Code Listing 10-6 (SubClass1.java) 1 public class SubClass1extends SuperClass1 2 { 3 /** 4 Constructor 5 */ 6 7 public SubClass1() 8 { 9 System.out.println("This is the " + 10 "subclass constructor."); 11 } 12 }
Code Listing 10-7 (ConstructorDemo1.java) 1 /** 2 This program demonstrates the order in which 3 superclass and subclass constructors are called. 4 */ 5 6 public class ConstructorDemo1 7 { 8 public static void main(String[] args) 9 { 10 SubClass1obj = new SubClass1(); 11 } } Program Output This is the superclass constructor. This is the subclass constructor.
Code Listing 10-8 (SuperClass2.java) 1 public class SuperClass2 2 { 3 /** 4 Constructor #1 No-ARG 5 */ 6 7 public SuperClass2() 8 { 9 System.out.println("This is the superclass " + 10 "no-arg constructor."); 11 } 12 13 /** 14 Constructor #2 Accepts an Int 15 */ 16 17 public SuperClass2( intarg) 18 { System.out.println ("The following argument was passed to the superclass " + 21 "constructor: " + arg); 22 } 23 }
Code Listing 10-9 (SubClass2.java) 1 public class SubClass2extends SuperClass2 2 { 3 /** 4 Constructor 5 */ 6 7 public SubClass2() 8 { super(10); //What if not included? 10 System.out.println("This is the " + 11 "subclass constructor."); 12 } 13 }
Code Listing 10-10 (ConstructorDemo2.java) 1 /** 2 This program demonstrates how a superclass 3 constructor is called with the “super” key word. 4 */ 5 6 public class ConstructorDemo2 7 { 8 public static void main(String[] args) 9 { 10 SubClass2obj= new SubClass2(); 11 } } Program Output The following argument was passed to the superclass constructor: 10 This is the subclass constructor.
Code Listing 10-11 (Cube.java) 1 /** 2 This class holds data about a cube. 3 */ 4 5 public class Cubeextends Rectangle 6 { 7 private double height; // The cube's height 8 9 /** 10 The constructor sets the cube's length, 11 width, and height. 12 @param len The cube's length. 13 @param w The cube's width. 14 @param h The cube's height. 15 */ 16 17 public Cube(double len, double w, double h) 18 { 19 // Call the superclass constructor. 20 super(len,w); // What if SUPER was not coded? 21 // WHY? 22 // Set the height. What must you know to answer? (Continued)
23 height = h; 24 } 25 26 /** 27 The getHeight method returns the cube's height. 28 @return The value in the height field. 29 */ 30 31 public double getHeight() 32 { 33 return height; 34 } 35 36 /** 37 The getSurfaceArea method calculates and 38 returns the cube's surface area. 39 @return The surface area of the cube. 40 */ 41 42 public double getSurfaceArea() 43 { 44 return getArea() * 6; // Where is getArea() defined? (Continued)
45 } 46 47 /** 48 The getVolume method calculates and 49 returns the cube's volume. 50 @return The volume of the cube. 51 */ 52 53 public double getVolume() 54 { 55 return getArea() * height; 56 } 57 }
Code Listing 10-12 (CubeDemo.java) 1 import java.util.Scanner; 2 3 /** 4 This program demonstratespassing arguments to a 5 superclass constructor. 6 */ 7 8 public class CubeDemo 9 { 10 public static void main(String[] args) 11 { 12 double length; // The cube's length 13 double width; // The cube's width 14 double height; // The cube's height 15 16 17 Scanner keyboard = new Scanner(System.in); 18 19 20 System.out.println("Enter the following " + 21 "dimensions of a cube:"); 22 System.out.print("Length: "); (Continued)
23 length = keyboard.nextDouble(); 24 25 26 System.out.print("Width: "); 27 width = keyboard.nextDouble(); 28 29 30 System.out.print("Height: "); 31 height = keyboard.nextDouble(); 32 33 // Create a cube object 34 35 CubemyCube = 36 new Cube(length, width, height); // Calls SubClass Constructor 37 // Display the cube's properties. 39 System.out.println("Here are the cube's " + 40 "properties."); 41 System.out.println("Length: " + 42 myCube.getLength()); // Inherited 43 System.out.println("Width: " + 44 myCube.getWidth()); // Inherited (Continued)
45 System.out.println("Height: " + 46 myCube.getHeight()); // Local 47 System.out.println("Base Area: " + 48 myCube.getArea()); // Inherited 49 System.out.println("Surface Area: " + 50 myCube.getSurfaceArea()); // Local 51 System.out.println("Volume: " + 52 myCube.getVolume()); // Local 53 } 54 } Program Output with Example Input Shown in Bold Enter the following dimensions of a cube: Length: 10 [Enter] Width: 15 [Enter] Height: 12 [Enter] Here are the cube's properties. Length: 10.0 Width: 15.0 Height: 12.0 Base Area: 150.0 Surface Area: 900.0 Volume: 1800.0
Code Listing 10-13 (CurvedActivity.java) 1 /** 2 This class computes a curved grade. It extends 3 the GradedActivity class. 4 */ 5 6 public class CurvedActivityextends GradedActivity 7 { 8 double rawScore; // Unadjusted score 9 double percentage; // Curve percentage 10 11 /** 12 The constructor sets the curve percentage. 13 @param percent The curve percentage. 14 */ 15 16 public CurvedActivity(double percent) // First Calls? - Why? 17 { // Does it pass any arguments? 18 percentage = percent; 19 rawScore= 0.0; 20 } 21 22 /** (Continued)
23 The setScore method overrides the superclass 24 setScore method. This version accepts the 25 unadjusted score as an argument. That score is 26 multiplied by the curve percentage and the 27 result is sent as an argument to the superclass's 28 setScore method. 29 @param s The unadjusted score. 30 */ 31 32 public void setScore(double s) 33 { 34 rawScore = s; 35 super.setScore(rawScore * percentage); 36 } 37 38 /** 39 The getRawScore method returns the raw score. 40 @return The value in the rawScore field. 41 */ 42 43 public double getRawScore() 44 { (Continued)
45 return rawScore; 46 } 47 48 /** 49 The getPercentage method returns the curve 50 percentage. 51 @return The value in the percentage field. 52 */ 53 54 public double getPercentage() 55 { 56 return percentage; 57 } 58 }
Code Listing 10-14 (CurvedActivityDemo.java) 1 import java.util.Scanner; 2 3 /** 4 This program demonstratesthe CurvedActivity class, 5 which inherits from the GradedActivity class. 6 */ 7 8 public class CurvedActivityDemo 9 { 10 public static void main(String[] args) 11 { 12 double score; // Raw score 13 double curvePercent; // Curve percentage 14 15 16 Scanner keyboard = new Scanner(System.in); 17 18 19 System.out.print("Enter the student's " + 20 "raw numeric score: "); 21 score= keyboard.nextDouble(); 22 (Continued)
23 24 System.out.print("Enter the curve percentage: "); 25 curvePercent= keyboard.nextDouble(); 26 27 28 CurvedActivitycurvedExam = newCurvedActivity(curvePercent); // Called? 30 31 32 curvedExam.setScore(score); // Called which method? Why? 33 34 // Display the raw score. 35 System.out.println("The raw score is " + curvedExam.getRawScore() + 37 " points."); 38 39 // Display the curved score. 40 System.out.println("The curved score is " + curvedExam.getScore()); // Inherited. 42 43 // Display the exam grade. System.out.println("The exam grade is " + curvedExam.getGrade()); // Inherited. 45 } 47 } // end class
Program Output with Example Input Shown in Bold Enter the student's raw numeric score: 87 [Enter] Enter the curve percentage: 1.06 [Enter] The raw score is 87.0 points. The curved score is 92.22 The exam grade is A
Code Listing 10-15 (SuperClass3.java) 1 public class SuperClass3 2 { /** 4 This method displays an int. 5 @paramarg An int. 6 */ 7 8 public void showValue( intarg ) // Overridden in subclass { // Can this be called through a subclass // Object? 10 System.out.println("SUPERCLASS: " + 11 "The int argument was " + arg); 12 } 13 14 /** 15 This method displays a String. Is showValue “overloaded in this class? 16 @paramarg A String. 17 */ 18 19 public void showValue( Stringarg )20 { 21 System.out.println("SUPERCLASS: " + 22 "The String argument was " + arg); 23 } 24 }
Code Listing 10-16 (SubClass3.java) 1 public class SubClass3extends SuperClass3 2 { 3 /** 4 This method overridesone of the 5 superclass methods. 6 @paramarg An int. 7 */ 8 9 public void showValue( intarg) // <-This May be called thru? { // <-addsuper.showvalue(arg); // AND What is impact? 11 System.out.println("SUBCLASS: " + 12 "The int argument was " + arg); 13 } 14 15 /** 16 This method overloads the superclass 17 methods. 18 @paramarg A double. 19 */ 20 21 public void showValue( double arg) // May be called thru? 22 { (Continued)
23 System.out.println("SUBCLASS: " + 24 "The double argument was " + arg); 25 } 26 }
Code Listing 10-17 (ShowValueDemo.java) 1 /** 2 This program demonstratesthe methods in the 3 SuperClass3 and SubClass3 classes. 4 */ 5 6 public class ShowValueDemo 7 { 8 public static void main(String[] args) 9 { 10 11 SubClass3myObject = new SubClass3(); 12 13 myObject.showValue( 10 ); // Pass an int. ALL 3 ARE CALLS 14 myObject.showValue( 1.2 ); // Pass a double. THRU A SUBCLASS 15 myObject.showValue( "Hello“ ); // Pass a String. OBJECT. 16 } 17 } Program Output SUBCLASS: The int argument was 10 // How would you call SUBCLASS: The double argument was 1.2 // Superclass method SUPERCLASS: The String argument was Hello // showvalue(intarg) ? See pg. 648(earlier slide)
Code Listing 10-18 (GradedActivity2.java) 1 /** 2 A class that holds a grade for a graded activity. 3 */ 4 5 public class GradedActivity2 6 { 7 protecteddouble score; // Numeric score 8 9 /** 10 The setScore method sets the score field. 11 @param s The value to store in score. 12 */ 13 14 public void setScore(double s) 15 { 16 score = s; 17 } 18 19 /** 20 The getScore method returns the score. 21 @return The value stored in the score field. 22 */ (Continued)
23 24 public double getScore() 25 { 26 returnscore; 27 } 28 29 /** 30 The getGrade method returns a letter grade 31 determined from the score field. 32 @return The letter grade. 33 */ 34 35 public char getGrade() 36 { 37 charletterGrade; 38 39 if (score >= 90) 40 letterGrade = 'A'; 41 else if (score >= 80) 42 letterGrade = 'B'; 43 else if (score >= 70) 44 letterGrade = 'C'; (Continued)
45 else if (score >= 60) 46 letterGrade = 'D'; 47 else 48 letterGrade = 'F'; 49 50 return letterGrade; 51 } 52 }
Code Listing 10-19 (FinalExam2.java) 1 /** 2 This class determines the grade for a final exam. 3 The numeric score is rounded up to the next whole 4 number if its fractional part is .5 or greater. 5 */ 6 7 public class FinalExam2extends GradedActivity2 8 { 9 private int numQuestions; // Number of questions 10 private double pointsEach; // Points for each question 11 private int numMissed; // Number of questions missed 12 13 /** 14 The constructor sets the number of questions on the 15 exam and the number of questions missed. 16 @param questions The number of questions. 17 @param missed The number of questions missed. */ // Constructor Code 19 //----------------------------------------------------------------------------------------------------- 20 public FinalExam2( int questions, int missed ) 21 { 22 double numericScore; // To hold a numeric score (Continued)
23 // Set the numQuestions and numMissed fields. 25 numQuestions = questions; 26 numMissed = missed; 27 28 // Calculate the points for each question and // the numeric score for this exam. 30 pointsEach = 100.0 / questions; 31 numericScore= 100.0 - (missed * pointsEach); 32 33 // Call the inherited setScore method to // set the numeric score. 35 setScore( numericScore ); // Inherited? 36 // Adjust the score. 38 adjustScore();// Where is method defined? 39 }//--------------------------------------------------------------------------------------------------- 40 41 /** 42 The getPointsEach method returns the number of 43 points each question is worth. 44 @return The value in the pointsEach field. (Continued)
45 */ 46 47 public double getPointsEach() 48 { 49 return pointsEach; 50 } 51 52 /** 53 The getNumMissed method returns the number of 54 questions missed. 55 @return The value in the numMissed field. 56 */ 57 58 public int getNumMissed() 59 { 60 return numMissed; 61 } 62 63 /** 64 The adjustScore method adjusts a numeric score. 65 If score is within 0.5 points of the next whole 66 number, it rounds the score up. (Continued)
67 */ 68 69 private void adjustScore()// Called from constructor 70 {// Why is “score”directlyavailable to this 71 double fraction; // method? 72 // Get the fractional part of the score. 74 fraction = score- (int) score; 75 76 // If the fractional part is .5 or greater, // round the score up to the next whole number. 78 if (fraction >= 0.5) 79 score= score+ (1.0 - fraction); 80 } 81 } // end class
Code Listing 10-20 (ProtectedDemo.java) 1 import javax.swing.JOptionPane; 2 3 /** 4 This program demonstrates the FinalExam2 class, 5 which extends the GradedActivity2 class. 6 */ 7 8 public class ProtectedDemo 9 { 10 public static void main(String[] args) 11 { 12 String input; // To hold input 13 intquestions; // Number of questions 14 Intmissed; // Number of questions missed 15 16 17 input = JOptionPane.showInputDialog("How many " + 18 "questions are on the final exam?"); 19 questions= Integer.parseInt(input); 20 21 22 input = JOptionPane.showInputDialog("How many " + (Continued)
23 "questions did the student miss?"); 24 missed= Integer.parseInt(input); 25 // Create a FinalExam object. 27 FinalExam2exam= new FinalExam2( questions,missed ); 28 // Display the test results. 30 JOptionPane.showMessageDialog(null, 31 "Each question counts " + exam.getPointsEach() + 32 " points.\nThe exam score is " + 33 exam.getScore() + "\nThe exam grade is " + 34 exam.getGrade()); 35 36 System.exit(0); 37 } 38 }
Code Listing 10-21 (PassFailActivity.java) 1 /** 2 This class holds a numeric score and determines 3 whether the score is passing or failing. 4 */ 5 6 public class PassFailActivityextends GradedActivity 7 { 8 private double minPassingScore; // Minimum passing score 9 10 /** 11 The constructor sets the minimum passing score. 12 @param mps The minimum passing score. 13 */ 14 15 public PassFailActivity( double mps) 16 { 17 minPassingScore = mps; 18 } 19 20 /** 21 The getGrade method returns a letter grade 22 determined from the score field. This (Continued)
23 method overrides the superclass method. 24 @return The letter grade. 25 */ 26 27 public char getGrade() // OVERRIDES supercalss method 28 { 29 char letterGrade; 30 31 if (super.getScore() >= minPassingScore) 32 letterGrade = 'P'; 33 else 34 letterGrade = 'F'; 35 36 return letterGrade; 37 } 38 }
Code Listing 10-22 (PassFailExam.java) 1 /** 2 This class determines a passing or failing grade for 3 an exam. 4 */ 5 6 public class PassFailExamextends PassFailActivity 7 { 8 private int numQuestions; // Number of questions 9 private double pointsEach; // Points for each question 10 private int numMissed; // Number of questions missed 11 12 /** 13 The constructor sets the number of questions, the 14 number of questions missed, and the minimum passing 15 score. 16 @param questions The number of questions. 17 @param missed The number of questions missed. 18 @param minPassing The minimum passing score. 19 */ 20 21 public PassFailExam( int questions, int missed, 22 double minPassing ) (Continued)
23 { 24 25 super( minPassing ); // Does what? Required? 26 27 / 28 double numericScore; 29 // Set the numQuestions and numMissed fields. 31 numQuestions= questions; 32 numMissed = missed; 33 34 // Calculate the points for each question and // the numeric score for this exam. 36 pointsEach = 100.0 / questions; 37 numericScore = 100.0 - (missed * pointsEach); 38 39 // Call the superclass's setScore method to // set the numeric score. 41 setScore( numericScore ); 42 } 43 44 /** (Continued)
45 The getPointsEach method returns the number of 46 points each question is worth. 47 @return The value in the pointsEach field. 48 */ 49 50 public double getPointsEach() 51 { 52 return pointsEach; 53 } 54 55 /** 56 The getNumMissed method returns the number of 57 questions missed. 58 @return The value in the numMissed field. 59 */ 60 61 public int getNumMissed() 62 { 63 return numMissed; 64 } 65 }
Code Listing 10-23 (PassFailExamDemo.java) 1 import java.util.Scanner; 2 3 /** 4 This program demonstrates the PassFailExam class. 5 */ 6 7 public class PassFailExamDemo 8 { 9 public static void main(String[] args) 10 { 11 int questions; // Number of questions 12 int missed; // Number of questions missed 13 double minPassing // Minimum passing score 14 15 // Create a Scanner object for keyboard input. 16 Scanner keyboard = new Scanner(System.in); 17 18 // Get the number of questions on the exam. 19 System.out.print("How many questions are " + 20 "on the exam? "); 21 questions = keyboard.nextInt(); 22 (Continued)
24 System.out.print("How many questions did " + 25 "the student miss? "); 26 missed = keyboard.nextInt(); 27 28 29 System.out.print("What is the minimum " + 30 "passing score? "); 31 minPassing = keyboard.nextDouble(); 32 // Create a PassFailExam object. 34 PassFailExam exam = new PassFailExam( questions, missed, minPassing ); 36 37 38 System.out.println("Each question counts " + 39 exam.getPointsEach() + " points."); 40 41 42 System.out.println("The exam score is " + 43 exam.getScore()); 44 (Continued)
45 46 System.out.println("The exam grade is " + 47 exam.getGrade()); 48 } 49 } Program Output with Example Input Shown in Bold How many questions are on the exam?100 [Enter] How many questions did the student miss?25 [Enter] What is the minimum passing score?60 [Enter] Each question counts 1.0 points. The exam score is 75.0 The exam grade is P