Question

Look at this partial class definition, and then answer questions a - b below: Class Book...

  1. Look at this partial class definition, and then answer questions a - b below:

Class Book

   Private String title

   Private String author

   Private String publisher

   Private Integer copiesSold

End Class

  1. Write a constructor for this class. The constructor should accept an argument for each of the fields.
  2. Write accessor and mutator methods for each field.
  1. Look at the following pseudocode class definitions:

Class Plant

   Public Module message()

      Display "I'm a plant."

   End Module

End Class

Class Tree Extends Plant

   Public Module message()

      Display "I'm a tree."

   End Module

End Class

Given these class definitions, what will the following pseudocode display? Explain why!

Declare Plant p

Set p = New Tree()

Call p.message()

  1. Most teachers assign various graded activities for their students to complete. A graded activity can be given a numeric score such as 70, 85, 90, and so on, and a letter grade such as A, B, C, D, or F. The GradedActivity class below is designed to hold the numeric score of a graded activity. The setScore method sets a numeric score, and the getScore method returns the numeric score. The getGrade method returns the letter grade that corresponds to the numeric score.

    Class GradedActivity

       // The score field holds a numeric score.

       Private Real score

       // Mutator

       Public Module setScore(Real s)

          Set score = s

       End Module

       // Accessor

       Public Function Real getScore()

          Return score

       End Function

       // getGrade method

       Public Function String getGrade()

          // Local variable to hold a grade.

          Declare String grade

          // Determine the grade.

          If score >= 90 Then

             Set grade = "A"

          Else If score >= 80 Then

             Set grade = "B"

          Else If score >= 70 Then

             Set grade = "C"

          Else If score >= 60 Then

             Set grade = "D"

          Else

             Set grade = "F"

          End If

          // Return the grade.

          Return grade

       End Function

    End Class

Write the GradedActivity class and the main() method below in Python. Run the program which will create an object from the GradedActivity class. Copy a screenshot of your Python program and output window and paste into your answer document.

   Module main()

       // A variable to hold a test score.

       Declare Real testScore

       // A class variable to reference a

       // GradedActivity object.

       Declare GradedActivity test

       // Create a GradedActivity object.

       Set test = New GradedActivity()

       // Get a test score from the user.

       Display "Enter a numeric test score."

       Input testScore

       // Store the test score in the object.

       test.setScore(testScore)

       // Display the grade for the object.

       Display "The grade for that test is ",

                test.getGrade()

    End Module

  1. Extend the GradedActivity class to create a new class FinalExam. Add the number of questions on an exam and the number missed. The class will calculate how many points each question is worth (out of exam score of 100) and calculate the score. Create the main() module to create a FinalExam object. Copy a screenshot of your Python program and output window and paste into your answer document.

    Class FinalExam Extends GradedActivity

       // Fields

       Private Integer numQuestions

       Private Real pointsEach

       Private Integer numMissed

       // The constructor sets the number of

       // questions on the exam and the number

       // of questions missed.

       Public Module FinalExam(Integer questions,

                               Integer missed)

           // Local variable to hold the numeric score.

           Declare Real numericScore

           // Set the numQuestions and numMissed fields.

           Set numQuestions = questions

           Set numMissed = missed

           // Calculate the points for each question

           // and the numeric score for this exam.

           Set pointsEach = 100.0 / questions

           Set numericScore = 100.0 - (missed * pointsEach)

  

           // Call the inherited setScore method to

           // set the numeric score.

           Call setScore(numericScore)

       End Module

       // Accessors

       Public Function Real getPointsEach()

           Return pointsEach

        End Function

        Public Function Integer getNumMissed()

           Return numMissed

        End Function

    End Class

The constructor for FinalExam may be tricky for you, so here is the Python code.

   def __init__(self, questions, missed):

       numericScore = 0.0

       self.numQuestions = questions

       self.numMissed = missed

       self.pointsEach = 100.0 / questions

       numericScore = 100.0 - (missed * self.pointsEach)

       GradedActivity.setScore(self, numericScore)

    Module main()

       // Variables to hold user input.

       Declare Integer questions, missed

       // Class variable to reference a FinalExam object.

       Declare FinalExam exam

       // Prompt the user for the number of questions

       // on the exam.

       Display "Enter the number of questions on the exam."

       Input questions

       // Prompt the user for the number of questions

       // missed by the student.

       Display "Enter the number of questions that the ",

               "student missed."

       Input missed

       // Create a FinalExam object.

       Set exam = New FinalExam(questions, missed)

       // Display the test results.

       Display "Each question on the exam counts ",

                exam.getPointsEach(), " points."

       Display "The exam score is ", exam.getScore()

       Display "The exam grade is ", exam.getGrade()

    End Module

  1. Design a class named Song, which should have the following fields:
  • title: The title field holds the name of a song.
  • artist: The artist field holds the artist of the song.
  • duration: The duration field holds the length of the song in seconds.

The Song class should also have the following methods:

  • setTitle: The setTitle method stores a value in the title field.
  • setArtist: The setArtist method stores a value in the artist field.
  • setDuration: The setDuration method stores a value in the duration field.
  • getTitle: The getTitle method returns the value of the title field.
  • getArtist: The getArtist method returns the value of the artist field.
  • getDuration: The getDuration method returns the value of the duration field.

Once you have designed the class, design a program (the main() method) that creates an object of the class and prompts the user to enter the title, artist, and duration of his or her song. This data should be stored in the object. Use the object’s accessor methods to retrieve the song’s title, artist, and duration (in seconds) and display this data on the screen. Consider the UX!

Copy a screenshot of your Python program and output window and paste into your answer document.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1) The constructor, Accessor and Mutator Methods for the given class is as follows:

Class Book
   Private String title
   Private String author
   Private String publisher
   Private Integer copiesSold

   //Constructor
   Public Module Book(String bt,String ba,String bp,Integer cs)
      Set title = bt
      Set author = ba
      Set publisher = bp
      Set copiesSold = cs
   End Module

   //Accessors
   Public Function String getTitle()
      Return title
   End Function

   Public Function String getAuthor()
      Return author
   End Function

   Public Function String getPublisher()
      Return publisher
   End Function

   Public Function Integer getCopiesSold()
      Return copiesSold
   End Function

   //Mutators
   Public Module setTitle(String t)
      Set title = t
   End Module

   Public Module setAuthor(String a)
      Set author = a
   End Module

   Public Module setPublisher(String p)
      Set publisher = p
   End Module

   Public Module setCopiesSold(Integer c)
      Set copiesSold = c
   End Module
End Class

2) Class Definition:

Class Plant
   Public Module message()
      Display "I'm a plant."
   End Module
End Class

Class Tree Extends Plant
   Public Module message()
      Display "I'm a tree."
   End Module
End Class

Given these class definitions, The pseudocode displays:

Declare Plant p
Set p = New Tree()
Call p.message()

Answer: I'm a tree.

Even though p is of Plant type, the reference assigned to it is of Tree Object and Tree is a type of Plant since it inherits features from Plant Class. The Tree class has overriden the message module. Hence the message "I'm a Tree." is displayed.

3) The python code corresponding to the GradedActivity Class and Main Module is as follows:

class GradedActivity:
    def setScore(self,s):
        self.score = s
    def getScore(self):
        return self.score
    def getGrade(self):
        if self.score>=90:
            grade = "A"
        elif self.score>=80:
            grade = "B"
        elif self.score>=70:
            grade = "C"
        elif self.score>=60:
            grade = "D"
        else:
            grade = "F"
        return grade

def main():   
    test = GradedActivity() # create object of GradedAcitivity class
    testScore = int(input("Enter a numeric score: ")) # ask user to enter a score
    test.setScore(testScore) #set the score using mutator method
    print('The grade for the test is', test.getGrade()) #print the grade using getGrade() method

main() #call the main function

OUTPUT:

4) The python code for FinalExam Class is as follows:

class GradedActivity:
    def setScore(self,s):
        self.score = s
    def getScore(self):
        return self.score
    def getGrade(self):
        if self.score>=90:
            grade = "A"
        elif self.score>=80:
            grade = "B"
        elif self.score>=70:
            grade = "C"
        elif self.score>=60:
            grade = "D"
        else:
            grade = "F"
        return grade

class FinalExam(GradedActivity):
    def __init__(self,questions,missed):
        self.numQuestions = questions
        self.numMissed = missed
        self.pointsEach = 100.0/questions
        numericScore = 100.0 - (missed*self.pointsEach)
        GradedActivity.setScore(self,numericScore)
    def getPointsEach(self):
        return self.pointsEach
    def getNumMissed(self):
        return self.numMissed

def main():
    questions = int (input ('Enter the number of questions on the exam: '))
    missed = int (input ('Enter the number of questions that the student missed: '))
    exam = FinalExam(questions,missed)
    print('Each question on the exam counts', exam.getPointsEach(), 'points.')
    print('The exam score is', exam.getScore())
    print('The exam Grade is', exam.getGrade())

main()

OUTPUT:

Add a comment
Know the answer?
Add Answer to:
Look at this partial class definition, and then answer questions a - b below: Class Book...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (1) Create two files to submit: Song.java - Class definition MainClass.java - Contains main() method (2)...

    (1) Create two files to submit: Song.java - Class definition MainClass.java - Contains main() method (2) Build the Song class in Song.java with the following specifications: Private fields String songTitle String songArtist int secDuration Initialize String fields to "Not defined" and numeric to 0. Create overloaded constructor to allow passing of 1 argument (title), 2 (title, artist) and 3 arguments (title, artist, duration). Create public member method printSongInfo () with output formatted as below: Title: Born in the USA Artist:...

  • Below is a class definition (.h) for the Bookclass. class Book { private:     int numPages;     string...

    Below is a class definition (.h) for the Bookclass. class Book { private:     int numPages;     string author;     string isbn;     double price; public:     string title;      public:     Book ();     void setAuthor(string);     string getAuthor();     void setIsbn(string);     string getIsbn ();     void setPrice(double);     double getPrice ();     string getTitle (); };                Assume you are writing code within the maindriver program: declare variable of type Book. Using the Bookvariable, set your book’s author to Edgar Allan Poe Using the Bookvariable, set your book’s title to The...

  • For Java please.Artwork. javaimport java.util.Scanner;public class ArtworkLabel {public static void main(String[] args)...

     Given main(). define the Artist class (in file Artist java) with constructors to initialize an artist's information, get methods, and a printlnfo() method. The default constructor should initialize the artist's name to "None' and the years of birth and death to 0. printinfo() should display Artist Name, born XXXX if the year of death is -1 or Artist Name (XXXX-YYYY) otherwise. Define the Artwork class (in file Artwork.java) with constructors to initialize an artwork's information, get methods, and a printinfo() method. The constructor should...

  • Info: The next question related to the Exam class whose definition (.h file) is shown below....

    Info: The next question related to the Exam class whose definition (.h file) is shown below. This Exam class represents a certain student’s test score. #include <string> namespace cs31 { class Exam { public: Exam ( std::string student, int score = 90 ); bool equal( const Exam & e1, const Exam & e2 ) const; int getScore() const; std::string getStudent() const; private: std::string mName; // Exam’s Student name int mScore; // Exam’s Student Score }; } 1a) Suppose we decide...

  • A. Create a CollegeCourse class. The class contains fields for the course ID (for example, CIS...

    A. Create a CollegeCourse class. The class contains fields for the course ID (for example, CIS 210), credit hours (for example, 3), and a letter grade (for example, A). Include get and set methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get and set method for the Student ID number. Also create a get method that returns one of the Student’s CollegeCourses; the method takes an integer...

  • A. Create a CollegeCourse class. The class contains fields for the course ID (for example, CIS...

    A. Create a CollegeCourse class. The class contains fields for the course ID (for example, CIS 210), credit hours (for example, 3), and a letter grade (for example, A). Include get and set methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get and set method for the Student ID number. Also create a get method that returns one of the Student’s CollegeCourses; the method takes an integer...

  • A. Create a CollegeCourse class. The class contains fields for the course ID (for example, CIS 21...

    A. Create a CollegeCourse class. The class contains fields for the course ID (for example, CIS 210), credit hours (for example, 3), and a letter grade (for example, A). Include get and set methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get and set method for the Student ID number. Also create a get method that returns one of the Student’s CollegeCourses; the method takes an integer...

  • Need help with the program DemoSugarSmash.java import java.util.*; public class DemoSugarSmash { public static void main(String[]...

    Need help with the program DemoSugarSmash.java import java.util.*; public class DemoSugarSmash { public static void main(String[] args) { // Complete the demo program here } } PremiumSugarSmashPlayer.java public class PremiumSugarSmashPlayer { // Define the PremiumSugarSmashPlayer class here } PremiumSugarSmashPlayer.java public class SugarSmashPlayer { private int playerID; private String screenName; private int[] scoresArray ; public SugarSmashPlayer() { this.scoresArray = new int[10]; } public SugarSmashPlayer(int levels) { this.scoresArray = new int[levels]; } public int getIdNumber() { return playerID; } public void setIdNumber(int...

  • Introduction In this final programming exercise, you'll get a chance to put together many of the...

    Introduction In this final programming exercise, you'll get a chance to put together many of the techniques used during this semester while incorporating OOP techniques to develop a simple song playlist class. This playlist class allows a user to add, remove and display songs in a playlist. The Base Class, Derived Class and Test Client Unlike the other PAs you completed in zyLabs, for this PA you will be creating THREE Java files in IntelliJ to submit. You will need...

  • JAVA /** * This class stores information about an instructor. */ public class Instructor { private...

    JAVA /** * This class stores information about an instructor. */ public class Instructor { private String lastName, // Last name firstName, // First name officeNumber; // Office number /** * This constructor accepts arguments for the * last name, first name, and office number. */ public Instructor(String lname, String fname, String office) { lastName = lname; firstName = fname; officeNumber = office; } /** * The set method sets each field. */ public void set(String lname, String fname, String...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT