workshop_9
.pdf
keyboard_arrow_up
School
University of Rochester *
*We aren’t endorsed by this school
Course
161
Subject
Computer Science
Date
Jan 9, 2024
Type
Pages
2
Uploaded by anonymousracoon1
Workshop 9
Classes
1. Write code to declare a class Person. A person has a name and a phone number. What
is the best way to represent a phone number? Include accessor (functions that get the
values), mutator (methods that let you change the values), and a constructor method.
2. Assume that you have the Person class defined from the previous question. Write the
code to declare a class RockBand. A rock band has four people (a singer, a drummer,
a guitar player, and a bass player). Include accessor, mutator, and constructor methods.
Assume that you have the two classes defined in the previous questions. Write a main
function that builds two different rock bands.
3. Modify the Student class, below, by adding a mutator method that records a grade for
the student. Here is the specification of the new method: addGrade(self, gradePoint,
credits) where gradePoint is a float value that represents a grade (e.g., A = 4.0, A- =
3.7, B+ = 3.3, etc.), and credits is a float value indicating the number of credit hours
for the class. Modify the student class by adding this grade information.
class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
def getName(self):
return self.name
def getHours(self):
return self.hours
def getQPoints(self):
return self.qpoints
def gpa(self):
return self.qpoints/self.hours
Use the updated class to implement a simple program for calculating GPA. Your pro-
gram should create a new student object that has 0 credits and 0 quality points (the
name is irrelevant). Then prompt the user to enter course information (gradePoint and
credits) and then print out the final GPA achieved.
1
4. Extend the previous exercise by implementing an addLetterGrade method.
This is
similar to addGrade except that it accepts a letter grade as a string (instead of a grade
point). Use the updated class to improve the GPA calculator by allowing the entry of
letter grades.
5. Write a class to represent the geometric solid sphere. Your class should implement the
following methods:
__init__(self, radius) # Creates a sphere given the radius.
getRadius(self) # Returns the radius of this sphere.
surfaceArea(self) # Returns the surface area of the sphere.
volume(self) # Returns the volume of the sphere.
Use this class to write a program that calculates the surface and the volume of a sphere
given its radius as input from the user.
2
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
PYTHON:
Define the Artist class with a constructor to initialize an artist's information and a print_info() method. The constructor should by default initialize the artist's name to "None" and the years of birth and death to 0. print_info() should display Artist Name, born XXXX if the year of death is -1 or Artist Name (XXXX-YYYY) otherwise.
Define the Artwork class with a constructor to initialize an artwork's information and a print_info() method. The constructor should by default initialize the title to "None", the year created to 0, and the artist to use the Artist default constructor parameter values.
Ex: If the input is:
Pablo Picasso 1881 1973 Three Musicians 1921
the output is:
Artist: Pablo Picasso (1881-1973) Title: Three Musicians, 1921
If the input is:
Brice Marden 1938 -1 Distant Muses 2000
the output is:
Artist: Brice Marden, born 1938 Title: Distant Muses, 2000
I have the code but I am getting errors that I can't seem to get rid of any suggestions would be appreciated
arrow_forward
Java Programming problem
Create a checking account class with three attributes: account number, owner’s name, and balance.
Create constructor, getters and setters. If one is to set the initial balance of an account as a negative value in a setter or a constructor, remind the user about the error and set it as 0.
Create a CheckingAccountDemo class, and create a main method in which
Ask for the name, account number, and initial balance for one account from the keyboard input. With these input values as arguments in a call to the constructor, create a CheckingAccount object.
Print the summary of this account that includes information on the name, account number, and balance by calling the getters.
arrow_forward
Code the StudentAccount class according to the class diagramMethods explanation:pay(double): doubleThis method is called when a student pays an amount towards outstanding fees. The balance isreduced by the amount received. The updated balance is returned by the method.addFees(double): doubleThis method is called to increase the balance by the amount received as a parameter. The updatedbalance is returned by the method.refund(): voidThis method is called when any monies owned to the student is paid out. This method can onlyrefund a student if the balance is negative. It displays the amount to be refunded and set thebalance to zero. (Use Math.abs(double) in your output message). If there is no refund, display anappropriate message.Test your StudentAccount class by creating objects and calling the methods addFees(), pay() andrefund(). Use toString() to display the object’s data after each method called
arrow_forward
Create a deck of cards class. Internally, the deck of cards should use another class, a card class. Your requirements are:
The Deck class should have a deal method to deal a single card from the deck
After a card is dealt, it is removed from the deck.
There should be a shuffle method which makes sure the deck of cards has all 52 cards and then rearranges them randomly.
The Card class should have a suit (Hearts, Diamonds, Clubs, Spades) and a value (A,2,3,4,5,6,7,8,9,10,J,Q,K)
arrow_forward
JAVA
Task
Write a JAVA class named Account to represent an account that you may find at a bank. Accounts have a balance and an annual interest rate. Include attributes in the Account class to reflect these.
Write getters for both attributes and a setter for only the annual interest rate. Think about how real bank accounts work, you change your balance by withdrawing and depositing money, not just by telling the banker how much you want to change it to.
Include a constructor with parameters used to assign values to both attributes.
Users should be able to withdraw money from an Account, deposit money into an Account, find monthly interest rate, and find monthy interest. Include methods for each of these actions. More details on them below.
withdraw method
This method simulates withdrawing money from the Account. It should not return a value and take the amount to withdraw as a parameter and reduce the balance by this amount.
deposit method
This method simulates depositing money into…
arrow_forward
Static class members are exactly what they sound like.
When and how can they be used?
arrow_forward
java programming language
You are part of a team writing classes for the different game objects in a video game. You need to write classes for the two human objects warrior and politician. A warrior has the attributes name (of type String) and speed (of type int). Speed is a measure of how fast the warrior can run and fight. A politician has the attributes name (of type String) and diplomacy (of type int). Diplomacy is the ability to outwit an adversary without using force.
From this description identify a superclass as well as two subclasses. Each of these three classes need to have a default constructor, a constructor with parameters for all the instance variables in that class (as well as any instance variables inherited from a superclass) accessor (get) and mutator (set) methods for all instance variables and a toString method. The toString method needs to return a string representation of the object. Also write a main method for each class in which that class is tested – create…
arrow_forward
Class 1: Bank Account (5 points)
Implement a class called BankAccount that is used to keep track of a bank account. This class will not have any methods
other than getters/setters. The class should have two private fields: one called 'balance' that represents how much
money is in the account, and one called id' that represents a unique number for the account.
Constructors
public BankAccountlint id, double
Creates a BankAccount object with an ID number and an initial
balance
initialBalance)
Methods
public int getld)
Returns the ID of the account.
public void
setBalance(double
Sets the balance member
balance)
public double
Returns the balance
getBalancel)
Returns a String to print information about the object in the format "Account ID: * Balance:
", where are the id and balance members.
public String toString()
In the main method:
1. Instantiate a BankAccount object using the constructor you created.
2. Print out the result of the object's getld() and getBalance() methods.
3. Call…
arrow_forward
Part 1
Java
Create a UML class diagram for the Circle class as described below:
radius: a double
PI: a final double initialized with the value 3.14159
The class should have the following methods:
a constructor that takes the radius of the circle
getRadius – An accessor (getter) for the radius
setRadius - A mutator (setter) method for the radius
calculateArea - Returns the area of the circle, which is calculated as:
area = PI * radius * radius
calculateDiameter - Returns the diameter of the circle, which is calculated as:
diameter = radius * 2
calculateCircumference - Returns the circumference of the circle, which is calculated as:
circumference = 2 * PI * radius
Create test data for several different Circle objects and calculate the expected results of calling the various methods.
Input
Expected Results
radius
Area
Diameter
Circumference
arrow_forward
Java Programming
Create your own class that illustrates the use of encapsulation. Make sure to include at least one setter and one getter for the class
arrow_forward
PYTHON CLASSES AND OBJECT
arrow_forward
Using JAVA
Part A) Design a class Message that models an e-mail message. A message has a recipient, a sender, and a message text. Support the following methods:
1) A constructor that takes the sender and recipient.
2) A method append that appends a line of text to the message body
A method toString that makes the message into one long string like: “From: Harry Morgan%nTo: Rudolf Reindee%n . . . “
Write a program that uses this class to make a message and print it.
Part B) Design a class Mailbox that stores e-mail messages, using the Message class in part a) Implement the following methods in the Message class.
public void addMessage(Message m) // Adds Message M to the Mailbox
public Message getMessage(int i) // returns the ith message from the Mailbox
public void removeMessage(int i) // removes the ith message from the Mailbox
public int mailBoxSize () // returns the number of messages in the Mailbox
Write a program to demonstrate the functionality of the Mailbox. Add messages to…
arrow_forward
java languageCreate a class with following attributes:
The car's make
The car's model
The car's year
Now let's identify the class's methods. Specifically, the actions are:
Constructor of Car class
Set and get the car's make
Set and get the car's model
Set and get the car's year
Now create few instance of the Car in a Test class. Use getter and setter to set the instance variables.
Create a class with following attributes:
The car's make
The car's model
The car's year
Now let's identify the class's methods. Specifically, the actions are:
Constructor of Car class
Set and get the car's make
Set and get the car's model
Set and get the car's year
Now create few instance of the Car in a Test class. Use getter and setter to set the instance variables.
arrow_forward
Shape Classes
Design classes Square, RightTriangle , and Triangle that encapsulate three geometric shapes. Each class should
implement a method
void draw (int x, int y)
that “draws" a square, a right triangle, or an equilateral triangle (a triangle with three equal sides), respectively.
See Figure 2. The parameters x and y specify the relative position of the figure: y lines down and x spaces acro
from the current position of the screen cursor. The instance variables of each class are:
int rows , the number of rows that comprise the figure,
and
char character , the keyboard character used for drawing the figure.
Each shape of Figure 2 consists of five rows. The drawing characters are *** for the square, %' for the right
triangle, and #' for the equilateral triangle.
Shape (abstract)
int rows
char character
Shape()
Shape(int x, char c)
int get rows()
char getCharacter()
void setRows(int x)
void setCharacter(int x)
void draw(int x, int y) (abstract)
Square()
Square(int x, char ch)
void…
arrow_forward
Python only
arrow_forward
Static members of a class are... When and how can you take advantage of these opportunities?
arrow_forward
Object Oriented Programming in JAVA
You are part of a team writing classes for the different game objects in a video game. You need to write classes for the two human objects warrior and politician. A warrior has the attributes name (of type String) and speed (of type int). Speed is a measure of how fast the warrior can run and fight. A politician has the attributes name (of type String) and diplomacy (of type int). Diplomacy is the ability to outwit an adversary without using force.
From this description identify a superclass as well as two subclasses. Each of these three classes need to have a default constructor, a constructor with parameters for all the instance variables in that class (as well as any instance variables inherited from a superclass) accessor (get) and mutator (set) methods for all instance variables and a toString method. The toString method needs to return a string representation of the object. Also write a main method for each class in which that class is…
arrow_forward
java programming
Robot Class : a robot has a name , located at a point with integer coordinates , faces north , east , south , or west and keeps a record of all its movements positions . The class has the following methods : A default constructor that initializes robot's name to " Unknown ” , location to ( 0,0 ) , direction to North , and travelled distance to 0 , and simulated movements to null . A constructor that given robot's name , starting location , and facing direction , Accessor methods to access all the instance variables and the simulated movements of the robot Mutator methods that change the instance variables to given values and they made the change for only suitable values . tumLeft and turn Right methods that change the direction of the robot but not the location move method that moves the robot by one unit in the direction it is facing . get Travelled Distance method that retums how many units has the robot moved .
arrow_forward
CLASS declaration
We need to have a “class” created called ROOM that has width and length defined. This represents a rectangular room. From room we need to define:Bathroom, Livingroom, Bedroom and Kitchen.You also need to have methods that can calculate the area of the room and set the length and width.
Given that we have the following house :
Bedroom1 (L=15,W=10)
Bathroom1 (L=10,W=7)
Kitchen1(L=15, W= 10)
Livingroom1 (L=25,W=20)
Calculate the total area of the home based on adding all room areas together and DISPLAY the result.
|
|--------------------We also know that in a certain area in an area of homes. ALL homes are above 1000 square feet.Could the house above be located in this area in specific?
------------------------You must display your result including the square feet of the house above.
C++
comments
arrow_forward
⚫ Task 1: Create a Class
Tasks
Define a class named Person with attributes name and age. Write a method greet() that prints a greeting
message including the person's name and age.
⚫ Task 2: Rectangle Class
Create a class Rectangle that takes length and width as parameters. Add methods area() and perimeter() to
calculate and return the area and perimeter of the rectangle.
⚫ Task 3: Object Interaction
Create a Library class that contains a list of books and methods to add, remove, and list all books in the library.
• Task 4: Movie Class
Create a class Movie with attributes title, director, and rating. Add a method display_info() that prints the
movie's details and a method rate_movie(new_rating) to update the movie's rating.
• Task 5: Ticket Class(homework)
Define a class Ticket' with attributes event_name, date, and price. Add methods
apply_discount(discount_percentage) to reduce the price by a given percentage and display_ticket() to print
the ticket details including the final price…
arrow_forward
Add the following new constructor in the BMI class:/** Construct a BMI with the specified name, age, weight,* feet, and inches*/public BMI(String name, int age, double weight, double feet,double inches)
arrow_forward
answer for task 2 only the question also refers to some of the stuff on task 1 skip 1
Draw the UML class diagrams for the following classes:
An abstract Java class called Person that has the following attributes:
a String called idNumber
a Date called dateOfBirth representing the date of birth.
a String for name
A class called VaccineRecord with the following attributes:
an enum called type of VaccineType
a Date called date
a String called batchCode
A class called Patient that extends the Person class and has the following attributes and behaviours:
an ArrayList that contains VaccineRecord objects called vaccinationRecord
a public method called vaccinate that takes a VaccineRecord with the following signature:
public void vaccinate(VaccineRecord vaccineRecord);
a public boolean method called isVaccinated that returns whether or not the Patient has had a vaccine.
A MedicalPractitioner class that extends the Person class and has the following attributes and behaviours:
a…
arrow_forward
Design a class that holds the following personal data: name, address, age, and phone number. Write appropriate accessor and mutator methods. Also, write a program that creates three instances of the class. One instance should hold your information, and the other two should hold your friends’ or family members’ information.
arrow_forward
public class date
{
private int day; // from 1 to 31
private int month; // from 1 to 12
private int year; // from 2000 upwards
public void advance (); // move to next day
};
Implement a constructor that initializes new objects of date class to be set to the 1st of January 2000.
Implement setters for day, month, and year.
Implement the advance method, which moves to the next day, ensuring that all data members are updated appropriately.
arrow_forward
C#
Define a class Human with properties "first name" and "last name". Define the class Student inheriting Human, which has the property "mark". Define the class Worker inheriting Human with the property "wage" and "hours worked". Implement a "calculate hourly wage" method, which calculates a worker’s hourly pay rate based on wage and hours worked. Write the corresponding constructors and encapsulate all data in properties.
arrow_forward
Note: This is a Java program question.
Q#8: Create the class as shown in Class diagram. Date-day:int
-month:int
-year:int
+getDay():int
+getMonth():int
+getYear():int
+setDay(Day:int):void
+setMonth(Month:int):void
+setYear(Year:int):void
+setDate(Day:int, Month:int, Year:int):void day : must be between 1 and 31
month: must be between 1 and 12
year: must be greater than 1900
arrow_forward
1. Write the java code for the following class diagram. Mention the method overridden.
Vehicle
Car
void: stop()
int: speed()
int :speed()
void :m
age
arrow_forward
⚫ Task 1: Create a Class
Tasks
Define a class named Person with attributes name and age. Write a method greet() that prints a greeting
message including the person's name and age.
⚫ Task 2: Rectangle Class
Create a class Rectangle that takes length and width as parameters. Add methods area() and perimeter() to
calculate and return the area and perimeter of the rectangle.
⚫ Task 3: Object Interaction
Create a Library dass that contains a list of books and methods to add, remove, and list all books in the library.
• Task 4: Movie Class
Create a class Movie with attributes title, director, and rating. Add a method display_info() that prints the
movie's details and a method rate_movie (new_rating) to update the movie's rating.
• Task 5: Ticket Class (homework)
Define a class Ticket' with attributes event_name, date, and `price. Add methods
apply_discount(discount_percentage) to reduce the price by a given percentage and display_ticket()` to print
the ticket details including the final…
arrow_forward
JAVA programming language
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
Microsoft Visual C#
Computer Science
ISBN:9781337102100
Author:Joyce, Farrell.
Publisher:Cengage Learning,
Related Questions
- PYTHON: Define the Artist class with a constructor to initialize an artist's information and a print_info() method. The constructor should by default initialize the artist's name to "None" and the years of birth and death to 0. print_info() should display Artist Name, born XXXX if the year of death is -1 or Artist Name (XXXX-YYYY) otherwise. Define the Artwork class with a constructor to initialize an artwork's information and a print_info() method. The constructor should by default initialize the title to "None", the year created to 0, and the artist to use the Artist default constructor parameter values. Ex: If the input is: Pablo Picasso 1881 1973 Three Musicians 1921 the output is: Artist: Pablo Picasso (1881-1973) Title: Three Musicians, 1921 If the input is: Brice Marden 1938 -1 Distant Muses 2000 the output is: Artist: Brice Marden, born 1938 Title: Distant Muses, 2000 I have the code but I am getting errors that I can't seem to get rid of any suggestions would be appreciatedarrow_forwardJava Programming problem Create a checking account class with three attributes: account number, owner’s name, and balance. Create constructor, getters and setters. If one is to set the initial balance of an account as a negative value in a setter or a constructor, remind the user about the error and set it as 0. Create a CheckingAccountDemo class, and create a main method in which Ask for the name, account number, and initial balance for one account from the keyboard input. With these input values as arguments in a call to the constructor, create a CheckingAccount object. Print the summary of this account that includes information on the name, account number, and balance by calling the getters.arrow_forwardCode the StudentAccount class according to the class diagramMethods explanation:pay(double): doubleThis method is called when a student pays an amount towards outstanding fees. The balance isreduced by the amount received. The updated balance is returned by the method.addFees(double): doubleThis method is called to increase the balance by the amount received as a parameter. The updatedbalance is returned by the method.refund(): voidThis method is called when any monies owned to the student is paid out. This method can onlyrefund a student if the balance is negative. It displays the amount to be refunded and set thebalance to zero. (Use Math.abs(double) in your output message). If there is no refund, display anappropriate message.Test your StudentAccount class by creating objects and calling the methods addFees(), pay() andrefund(). Use toString() to display the object’s data after each method calledarrow_forward
- Create a deck of cards class. Internally, the deck of cards should use another class, a card class. Your requirements are: The Deck class should have a deal method to deal a single card from the deck After a card is dealt, it is removed from the deck. There should be a shuffle method which makes sure the deck of cards has all 52 cards and then rearranges them randomly. The Card class should have a suit (Hearts, Diamonds, Clubs, Spades) and a value (A,2,3,4,5,6,7,8,9,10,J,Q,K)arrow_forwardJAVA Task Write a JAVA class named Account to represent an account that you may find at a bank. Accounts have a balance and an annual interest rate. Include attributes in the Account class to reflect these. Write getters for both attributes and a setter for only the annual interest rate. Think about how real bank accounts work, you change your balance by withdrawing and depositing money, not just by telling the banker how much you want to change it to. Include a constructor with parameters used to assign values to both attributes. Users should be able to withdraw money from an Account, deposit money into an Account, find monthly interest rate, and find monthy interest. Include methods for each of these actions. More details on them below. withdraw method This method simulates withdrawing money from the Account. It should not return a value and take the amount to withdraw as a parameter and reduce the balance by this amount. deposit method This method simulates depositing money into…arrow_forwardStatic class members are exactly what they sound like. When and how can they be used?arrow_forward
- java programming language You are part of a team writing classes for the different game objects in a video game. You need to write classes for the two human objects warrior and politician. A warrior has the attributes name (of type String) and speed (of type int). Speed is a measure of how fast the warrior can run and fight. A politician has the attributes name (of type String) and diplomacy (of type int). Diplomacy is the ability to outwit an adversary without using force. From this description identify a superclass as well as two subclasses. Each of these three classes need to have a default constructor, a constructor with parameters for all the instance variables in that class (as well as any instance variables inherited from a superclass) accessor (get) and mutator (set) methods for all instance variables and a toString method. The toString method needs to return a string representation of the object. Also write a main method for each class in which that class is tested – create…arrow_forwardClass 1: Bank Account (5 points) Implement a class called BankAccount that is used to keep track of a bank account. This class will not have any methods other than getters/setters. The class should have two private fields: one called 'balance' that represents how much money is in the account, and one called id' that represents a unique number for the account. Constructors public BankAccountlint id, double Creates a BankAccount object with an ID number and an initial balance initialBalance) Methods public int getld) Returns the ID of the account. public void setBalance(double Sets the balance member balance) public double Returns the balance getBalancel) Returns a String to print information about the object in the format "Account ID: * Balance: ", where are the id and balance members. public String toString() In the main method: 1. Instantiate a BankAccount object using the constructor you created. 2. Print out the result of the object's getld() and getBalance() methods. 3. Call…arrow_forwardPart 1 Java Create a UML class diagram for the Circle class as described below: radius: a double PI: a final double initialized with the value 3.14159 The class should have the following methods: a constructor that takes the radius of the circle getRadius – An accessor (getter) for the radius setRadius - A mutator (setter) method for the radius calculateArea - Returns the area of the circle, which is calculated as: area = PI * radius * radius calculateDiameter - Returns the diameter of the circle, which is calculated as: diameter = radius * 2 calculateCircumference - Returns the circumference of the circle, which is calculated as: circumference = 2 * PI * radius Create test data for several different Circle objects and calculate the expected results of calling the various methods. Input Expected Results radius Area Diameter Circumferencearrow_forward
- Java Programming Create your own class that illustrates the use of encapsulation. Make sure to include at least one setter and one getter for the classarrow_forwardPYTHON CLASSES AND OBJECTarrow_forwardUsing JAVA Part A) Design a class Message that models an e-mail message. A message has a recipient, a sender, and a message text. Support the following methods: 1) A constructor that takes the sender and recipient. 2) A method append that appends a line of text to the message body A method toString that makes the message into one long string like: “From: Harry Morgan%nTo: Rudolf Reindee%n . . . “ Write a program that uses this class to make a message and print it. Part B) Design a class Mailbox that stores e-mail messages, using the Message class in part a) Implement the following methods in the Message class. public void addMessage(Message m) // Adds Message M to the Mailbox public Message getMessage(int i) // returns the ith message from the Mailbox public void removeMessage(int i) // removes the ith message from the Mailbox public int mailBoxSize () // returns the number of messages in the Mailbox Write a program to demonstrate the functionality of the Mailbox. Add messages to…arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningMicrosoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
Microsoft Visual C#
Computer Science
ISBN:9781337102100
Author:Joyce, Farrell.
Publisher:Cengage Learning,