Topic G – Raising Exceptions
Overview
This topic introduces the throw statement and exceptions. The following new keywords are introduced.
* throw
* throws
This topic will demonstrate objects that are capable of validating information supplied to them. This introduces the principle in object oriented design that well designed objects are capable of ensuring the validity of their internal state. When invalid information is supplied, either through the constructor or through other methods, objects can respond by raising exceptions.
LOGs
General Programming Concepts and Terms
- Describe how object-oriented programs run
- Describe what is meant by a “call stack”
- Define the term “Exception”
- Describe what is meant by the phrase “raising (or throwing) an exception”
- Describe the role that exceptions play in a computer program
- Identify the three most commonly used Exception types used in this course
OOP Basics
- Explain why methods (including constructors) should perform validation of their parameter values
- Explain the significance of raising an exception in the constructor
- Use exceptions as part of the validation of parameter values in methods and constructors
- Explain why property setters are a good place for throwing exceptions
- Identify when constructors should throw exceptions directly
Code Samples
- Fraction – The fraction class avoid the division by zero error by ensuring that the supplied denominator is not zero.
- Square – Only accepts positive, non-zero lengths for the side.
- Circle – Only accepts positive, non-zero diameters.
- Die – Only accepts from 4 to 20 sides for a die.
- Person – First and last names cannot be empty and the birth date cannot be in the future. This illustrates putting the validation on the setters and calling the setters from the constructor (to reduce the duplication of code).
- Student – Gender must be ‘M’ or ‘F’ (and will be converted to upper-case). The student name and program cannot be empty. The student ID must be 9 digits. The GPA must be between 0.0 and 9.0 (inclusive).
- ParkingCounter – Only accepts positive, non-zero counts for available parking spaces and number of cars. Also, the number of cars must not exceed the number of parking spaces. The rules for the number of cars must also apply for cars entering and leaving the parking lot.
- StockItem – Represents an inventory item that is kept in stock. The item’s description, cost and profit margin are all part of the class design. Empty descriptions and zero or negative costs, as well as profit margins less than -100, are not allowed.
- Account – The following account information is now verified when the class is created:
- Bank name and account type cannot be empty
- The opening balance must be greater than zero
- The overdraft limit cannot be negative
- The institution number must be 3 digits
- The branch number must be 6 digits
- Attempts to withdraw amounts beyond the overdraft limit should throw an “Insufficient Funds” exception
Fraction
The fraction class avoids the division by zero error by ensuring that the supplied denominator is not zero.
Problem Statement
Write the code for the Fraction class. The solution must meet the following requirements (new requirements are in bold):
* Should get the string representation of the fraction, as “numerator/denominator”
* Should get the numeric value of the fraction (as a real number)
* Should get the reciprocal of the fraction
* Should get the numerator and denominator
* Should add another fraction to its existing value
* Should subtract another fraction from its existing value
* Should multiply its existing value by another fraction
* Should divide its existing value by another fraction
* Should affix the sign for negative fractions onto the numerator only
* Should identify if the fraction is a proper fraction
* Should reject zero denominators
Use the following class diagram when creating your solution.
1 public Fraction(int numerator, int denominator)
2 {
3 if (denominator == 0)
4 throw new System.Exception("A fraction cannot have a denominator of \
5 zero (0)");
6 Numerator = numerator;
7 Denominator = denominator;
8 FixSign();
9 }
Square
Only accepts positive, non-zero lengths for the side.
Problem Statement
Write the code needed to add the ability for a Square to determine the length of its diagonal. The solution must meet the following requirements (new requirements are in bold):
* Should get and set the length of the side of the square
* Should calculate the area, perimeter, and diagonal of the square
* Should only accept positive, non-zero lengths for the side
Use the following class diagram when creating your solution.
1 private double _Side;
2 public double Side
3 {
4 get
5 {
6 return _Side;
7 }
8 set
9 {
10 if (value <= 0)
11 throw new System.Exception("A square must have a positive non-ze\
12 ro length for its side");
13 _Side = value;
14 }
15 }
Circle
Only accepts positive, non-zero diameters.
Problem Statement
Write the code for the Circle class. The solution must meet the following requirements (new requirements are in bold):
- Should get and set the diameter
- Should calculate the area, radius, and circumference
- Should only accept positive, non-zero lengths for the diameter
Use the following class diagram when creating your solution.
1 private double _Diameter;
2 public double Diameter
3 {
4 get
5 {
6 return _Diameter;
7 }
8 set
9 {
10 if (value <= 0)
11 throw new System.Exception("Diameter must be a positive non-zero\
12 value");
13 _Diameter = value;
14 }
15 }
Die
Only accepts from 4 to 20 sides for a die. This class represents a single six-sided die. This example is used to illustrate random number generation and casting.
Problem Statement
Write the code for the Die class. The solution must meet the following requirements (new requirements are in bold):
- Should generate a random value from 1 to the number of sides on the die, when initially created and when re-rolled
- Should get the face value of the die
- Should get the number of sides of the die
- Should randomly generate each side (if rolled enough); for example, if the die has ten sides, it should eventually roll a 1, 2, 3, 4, 5 6, 7, 8, 9, and 10
- Should only accept 4 to 20 sides for the die
Use the following class diagram when creating your solution.
1 public Die(int sides)
2 {
3 if (sides < 4 || sides > 20)
4 throw new System.Exception("A die can only have from 4 to 20 sides");
5 this.Sides = sides;
6 Roll();
7 }
Person
First and last names cannot be empty and the birth date cannot be in the future. This illustrates putting the validation on the setters and calling the setters from the constructor (to reduce the duplication of code).
This adaptation of the person class includes a check of the age of the person to see if the person’s life stage is infant, toddler, preschooler, school age, or adult.
Problem Statement
Write the code that will represent a person with a first and last name and a date of birth. The solution must meet the following requirements (new requirements are in bold):
- Should get and set the first and last name
- Should get the birth date
- Should get the person’s approximate age (which is the age that the person will turn to in the current year)
- Should override toString() to get the person’s full name (as first name then last name)
- Should get the life stage, based on the following table
| Age Range (Years) | Life Stage |
|---|---|
| 0 | Infant |
| < 3 | Toddler |
| < 5 | Preschooler |
| < 18 | School age |
| >= 18 | Adult |
- Should ensure the first and last names are not empty (or null)
- Should trim leading and trailing spaces from the first and last names
- Should reject birthdates that are in the future
Use the following class diagram when creating your solution.
1 private string _FirstName;
2 public string FirstName
3 {
4 get
5 {
6 return _FirstName;
7 }
8 set
9 {
10 if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim()\
11 ))
12 throw new Exception("FirstName cannot be empty");
13 _FirstName = value.Trim();
14 }
15 }
16
17 private string _LastName;
18 public string LastName
19 {
20 get
21 {
22 return _LastName;
23 }
24 set
25 {
26 if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim()\
27 ))
28 throw new Exception("LastName cannot be empty");
29 _LastName = value.Trim();
30 }
31 }
32
33 public Person(string firstName, string lastName, DateTime birthDate)
34 {
35 if (birthDate.CompareTo(DateTime.Today) > 0)
36 throw new System.Exception("Birthdates in the future are not allowed\
37 ");
38 FirstName = firstName;
39 LastName = lastName;
40 BirthDate = birthDate;
41 }
Student
Gender must be ‘M’ or ‘F’ (and will be converted to upper-case). The student name and program cannot be empty. The student ID must be 9 digits. The GPA must be between 0.0 and 9.0 (inclusive).
Problem Statement
Write the code for the Student class. The class must now ensure that the supplied information is valid. The solution must meet the following requirements (new requirements are in bold):
- Should get and set the student’s name, gender, GPA, program of studies, and whether or not the student is full-time.
- Should override the toString() method to get the student’s ID and name in this format:
(ID) Name - Should n * longer allow the student ID to be set (it’s only set through the constructor)
- Should reject empty text (and null values) for the student’s name and program of studies.
- Should trim the student’s name and the program name
- Should only accept ‘M’ and ‘F’ as valid genders
- Should set the gender to upper-case
- Should reject negative GPAs and GPAs over 9
- Should require a nine-digit student ID
This class reinforces the idea of encapsulation and constructors. It also demonstrates the idea of overloading the default ToString() method that every class inherits from the Object class.
1 public class Student
2 {
3 #region Fields
4 private string _Name;
5 private char _Gender;
6 private int _StudentId;
7 private string _Program;
8 private double _GradePointAverage;
9 private bool _IsFullTime;
10 #endregion
11
12 #region Properties
13 public string Name
14 {
15 get { return _Name; }
16 set
17 {
18 if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim()\
19 ))
20 throw new System.Exception("Name cannot be empty");
21 _Name = value.Trim();
22 }
23 }
24
25 public char Gender
26 {
27 get { return _Gender; }
28 set
29 {
30 value = char.ToUpper(value);
31 if (value != 'M' && value != 'F')
32 throw new Exception("Gender must be M or F");
33 _Gender = value;
34 }
35 }
36
37 public int StudentId
38 {
39 get { return _StudentId; }
40 set
41 {
42 if (value < 100000000 || value > 999999999)
43 throw new Exception("Student Ids must be 9 digits");
44 _StudentId = value;
45 }
46 }
47
48 public string Program
49 {
50 get { return _Program; }
51 set
52 {
53 if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim()\
54 ))
55 throw new Exception("Program cannot be empty");
56 _Program = value.Trim();
57 }
58 }
59
60 public double GradePointAverage
61 {
62 get { return _GradePointAverage; }
63 set
64 {
65 if (value < 0 || value > 9)
66 throw new System.Exception("GPA must be between 0 and 9 inclusiv\
67 e");
68 _GradePointAverage = value;
69 }
70 }
71
72 public bool IsFullTime
73 {
74 get { return _IsFullTime; }
75 set { _IsFullTime = value; }
76 }
77 #endregion
78
79 #region Constructors
80 public Student(string name, char gender, int studentId, string program, doub\
81 le gradePointAverage, bool isFullTime)
82 {
83 if (studentId < 100000000 || studentId > 999999999)
84 throw new System.Exception("Student Ids must be 9 digits");
85 this.Name = name;
86 this.Gender = gender;
87 this.StudentId = studentId;
88 this.Program = program;
89 this.GradePointAverage = gradePointAverage;
90 this.IsFullTime = isFullTime;
91 }
92 #endregion
93
94 #region Methods
95 public override string ToString()
96 {
97 return "(" + StudentId + ") " + Name;
98 }
99 #endregion
100 }
ParkingCounter
Only accepts positive, non-zero counts for available parking spaces and number of cars. Also, the number of cars must not exceed the number of parking spaces. The rules for the number of cars must also apply for cars entering and leaving the parking lot.
Problem Statement
Write the code that will monitor vehicles entering and leaving a parking lot. The solution must meet the following requirements (new requirements are in bold):
- Should track vehicles entering
- Should track vehicles leaving
- Should track the peak occupancy of the parking lot
- The peak occupancy represents the highest number of cars in the parking lot at any one time
- Should get total parking spots
- Should get open (empty) spots
- Should reset lot as full (that is, fill the parking lot)
- Should reset lot as empty (that is, clear all the parking spots of vehicles)
- Should only allow a positive (non-zero) number of parking spots
- Should not allow a negative number of cars (when using the overloaded constructor), and should not allow more cars than parking spots
-
Should not allow available (open) parking spots to go negative or to exceed the actual number of parking spots
- Should raise an error when trying to enter a full parking lot
- Should raise an error if trying to leave a parking lot that is already empty
Use the following class diagram when creating your solution.
1 public ParkingCounter(int parkingSpots)
2 {
3 if (parkingSpots <= 0)
4 throw new System.Exception("Negative or zero parkingSpots not allowe\
5 d");
6 this.ParkingSpots = parkingSpots;
7 this.OpenSpots = parkingSpots;
8 this.peak = 0;
9 }
10
11 public ParkingCounter(int parkingSpots, int numberOfCars)
12 {
13 if (parkingSpots <= 0)
14 throw new System.Exception("Negative or zero parkingSpots not allowe\
15 d");
16 if (numberOfCars < 0)
17 throw new System.Exception("Negative numberOfCars not allowed");
18 if (numberOfCars > parkingSpots)
19 throw new System.Exception("The number of cars cannot exceed the num\
20 ber of parking spots");
21 this.ParkingSpots = parkingSpots;
22 this.OpenSpots = this.ParkingSpots - numberOfCars;
23 this.peak = numberOfCars;
24 }
25
26 public void leave()
27 {
28 if (OpenSpots == ParkingSpots)
29 throw new System.Exception("Parking lot is empty");
30 OpenSpots++;
31 }
32
33 public void enter()
34 {
35 if (OpenSpots == 0)
36 throw new System.Exception("Parking lot is full");
37 OpenSpots--;
38 int numberOfCars = ParkingSpots - OpenSpots;
39 if (numberOfCars > peak)
40 peak = numberOfCars;
41 }
StockItem
The StockItem class represents an inventory item that is kept in stock. The item’s description, cost and profit margin are all part of the class design. Empty descriptions and zero or negative costs, as well as profit margins less than -100, are not allowed.
Problem Statement
Write the code for adding validation to the StockItem class. The solution must meet the following requirements (new requirements are in bold):
- Should get and set the name, cost and profit margin of the stock item
- Should represent the profit margin as a percent; a value of 45 means 45%
- Should calculate the price of the item, to the nearest cent
- Use the rounding where values under a half-cent are rounded down and values greater than or equal to a half-cent are rounded up
- Should recognize when the stock item is priced at cost (that is, the profit margin is zero)
- Should recognize when the stock item is priced below cost (that is, the profit margin is negative)
- Should reject an empty (or null) item name
- Should trim excess spaces from the ends of the item name
- Should require cost to be greater than zero
- Should only allow negative profit margins up to 100% (which is a full mark-down)
Use the following class diagram when creating your solution.
1 private double _Cost;
2 public double Cost
3 {
4 get
5 {
6 return _Cost;
7 }
8 set
9 {
10 if (value <= 0)
11 throw new Exception("Cost must be positive");
12 _Cost = value;
13 }
14 }
15
16 private double _ProfitMargin;
17 public double ProfitMargin
18 {
19 get
20 {
21 return _ProfitMargin;
22 }
23 set
24 {
25 if (value < -100)
26 throw new Exception("A profit margin below 100% (more than the c\
27 ost) is not allowed");
28 _ProfitMargin = value;
29 }
30 }
31
32 private string _ItemName;
33 public string ItemName
34 {
35 get
36 {
37 return _ItemName;
38 }
39 set
40 {
41 if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim()\
42 ))
43 throw new Exception("ItemName cannot be empty");
44 _ItemName = value.Trim();
45 }
46 }
Account
The following account information is now verified when the class is created:
- Bank name and account type cannot be empty
- The opening balance must be greater than zero
- The overdraft limit cannot be negative
- The institution number must be 3 digits
- The branch number must be 6 digits
- Attempts to withdraw amounts beyond the overdraft limit should throw an “Insufficient Funds” exception
Problem Statement
Write the code that will add validation to the Account class. The solution must meet the following requirements (new requirements are in bold):
* Should get the bank name, branch number, institution number, account number, balance, overdraft limit, and account type and allow the overdraft limit to be set
* Should support deposits
* Should only support withdrawals if the amount does not exceed the sum of the balance and the overdraft limit, otherwise an exception stating “Insufficient Funds” should occur
* Should identify if the account is overdrawn
* Should require bank name and account type (that is, they cannot be empty or null)
* Should trim the bank name and account type
* Should verify that the branch number is six digits and the institution number is three digits
* Should require an opening balance
* Should not allow a negative overdraft limit
Use the following class diagram when creating your solution.
1 public double Balance
2 {
3 get { return _Balance; }
4 set {
5 if (value < -OverdraftLimit)
6 throw new Exception("Negative balances cannot exceed the Overdra\
7 ft Limit");
8 _Balance = value;
9 }
10 }
11
12 public double OverdraftLimit
13 {
14 get { return _OverdraftLimit; }
15 set
16 {
17 if (value < 0)
18 throw new Exception("Negative overdraft limits not allowed");
19 _OverdraftLimit = value;
20 }
21 }
22
23 public int BranchNumber
24 {
25 get { return _BranchNumber; }
26 set {
27 if (value < 10000 || value > 99999)
28 throw new Exception("Branch number must be 5 digits");
29 _BranchNumber = value;
30 }
31 }
32
33 public int InstitutionNumber
34 {
35 get { return _InstitutionNumber; }
36 set
37 {
38 if (value < 100 || value > 999)
39 throw new Exception("InstitutionNumber must be a three-digit val\
40 ue");
41 _InstitutionNumber = value;
42 }
43 }
44
45 public string AccountType
46 {
47 get { return _AccountType; }
48 set {
49 if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim()\
50 ))
51 throw new Exception("Account type cannot be empty");
52 _AccountType = value.Trim();
53 }
54 }
55
56 public string BankName
57 {
58 get { return _BankName; }
59 set
60 {
61 if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(value.Trim()\
62 ))
63 throw new Exception("BankName is required");
64 _BankName = value.Trim();
65 }
66 }
67
68 public Account(string bankName, int branchNumber, int institutionNumber, int\
69 accountNumber, double balance, double overdraftLimit, string accountType)
70 {
71 if (balance <= 0)
72 throw new Exception("Opening balance must be greater than zero");
73 if (balance != Math.Round(balance, 2))
74 throw new Exception("Opening balances cannot include a fraction of a\
75 penny");
76 if (overdraftLimit != Math.Round(overdraftLimit, 2))
77 throw new Exception("Overdraft limit amounts cannot include a fracti\
78 on of a penny");
79 AccountNumber = accountNumber;
80 Balance = balance;
81 OverdraftLimit = overdraftLimit;
82 BankName = bankName;
83 BranchNumber = branchNumber;
84 InstitutionNumber = institutionNumber;
85 AccountType = accountType;
86 }
87
88 public double Withdraw(double amount)
89 {
90 if (amount != Math.Round(amount, 2))
91 throw new Exception("Withdrawal amounts cannot include fractions of \
92 a penny");
93 if (amount > Balance + OverdraftLimit)
94 throw new Exception("Insufficient Funds");
95 if (amount <= Balance + OverdraftLimit)
96 Balance = Math.Round(Balance - amount, 2);
97 else
98 amount = 0;
99 return amount;
100 }
101
102 public void Deposit(double amount)
103 {
104 if (amount != Math.Round(amount, 2))
105 throw new Exception("Deposit amounts cannot include fractions of a p\
106 enny");
107 Balance = Math.Round(Balance + amount, 2);
108 }
Practice Exercises
- Account – Add one more point of validation to the Account class: Do not allow depositing or withdrawing non-positive amounts.
- Rectangle – The height and width of the rectangle must be greater than zero.
- Cone – The radius and height of the cone must be greater than zero.
- Course – The course name and number cannot be blank, and the exam and lab counts must be greater than zero. The class hours must also be greater than zero.
- Cylinder – The radius and height of the cylinder must be greater than zero.
- HazardousMaterial – The class code for the hazardous material can only be the letters ‘A’ through ‘F’, inclusive.
- ExamResult - Requires a positive, non-zero value for the total marks and weight. The weight cannot be over 50. The marks earned can be between zero and the total marks, inclusive. The student ID must be 9 digits, and the exam name cannot be an empty string.
- LabResult – Requires a positive, non-zero value for the lab number, total marks and weight. The weight cannot be over 50. The marks earned can be between zero and the total marks, inclusive. The student ID must be 9 digits.
- PeopleCounter – Does not allow adding a negative number of people to the counter.
- BulkItem – The description cannot be blank and the cost and quantity values must be greater than zero.
Account
Problem Statement
Write the code that will add another piece of validation to the Account class. The solution must meet the following requirements (new requirements are in bold):
- Should get the bank name, branch number, institution number, account number, balance, overdraft limit, and account type and allow the overdraft limit to be set
- Should support deposits
- Should only support withdrawals if the amount does not exceed the sum of the balance and the overdraft limit, otherwise an exception stating “Insufficient Funds” should occur
- Should identify if the account is overdrawn
- Should require bank name and account type (that is, they cannot be empty or null)
- Should trim the bank name and account type
- Should verify that the branch number is six digits and the institution number is three digits
- Should require an opening balance
- Should not allow a negative overdraft limit
- Should only allow positive, non-zero amounts when performing a deposit or withdrawal
Use the following class diagram when creating your solution.
Rectangle
The height and width of the rectangle must be greater than zero.
Problem Statement
Write the code to provide validation for the Rectangle class. The solution must meet the following requirements (new requirements are in bold):
- Should get and set the height and the width
- Should calculate the area, the perimeter and the diagonal
- The formula for the diagonal is √(〖width〗2 + 〖height〗2 )
- Should determine if the rectangle is a square
- Should require the height and width to be greater than zero
Use the following class diagram when creating your solution.
Cone
The radius and height of the cone must be greater than zero.
Problem Statement
Write the code to provide validation for the Cone class that meets the following requirements (new requirements are in bold):
- Should get the radius and the height
- Should calculate the volume and the surface area
- Should require the radius and height to be greater than zero
Use the following class diagram when creating your solution.
Course
The course name and number cannot be blank, and the exam and lab counts must be greater than zero. The class hours must also be greater than zero.
Problem Statement
Write the code to provide validation for the Course class. The solution must meet the following requirements (new requirements are in bold):
- Should get the course name and number, the number of exams and labs, and the class hours for the course.
- Should not allow empty course names or numbers
- Should trim spaces from the course name and number
- Should require class hours as well as lab and exam counts to be greater than zero
Cylinder
The radius and height of the cylinder must be greater than zero.
Problem Statement
Write the code to provide validation for the Cylinder class that meets the following requirements (new requirements are in bold):
- Should get the radius and the height
- Should calculate the volume and the surface area
- Should make sure the radius and height are greater than zero
Use the following class diagram when creating your solution.
HazardousMaterial
The class code for the hazardous material can only be the letters ‘A’ through ‘F’, inclusive.
Problem Statement
Write the code to provide validation for the HazardousMaterial class. The solution must meet the following requirements (new requirements are in bold):
- Should return the class code as the classification
- Should make sure only class codes ‘A’ through ‘F’ are allowed (in either upper or lower case)
- Should make sure the classification is stored in upper case
- Should get the description for the class, based on the following table
| Class Code | Description |
|---|---|
| A | Compressed Gas |
| B | Flammable and Combustible Material |
| C | Oxidizing Material |
| D | Poisonous and Infectious Material |
| E | Corrosive Material |
| F | Dangerously Reactive Material |
- Should override the toString() method to get the full description and class code in the following format:
- “Class ClassCode - Description”
Use the following class diagram when creating your solution.
ExamResult
Requires a positive, non-zero value for the total marks and weight. The weight cannot be over 50. The marks earned can be between zero and the total marks, inclusive. The student ID must be 9 digits, and the exam name cannot be an empty string.
Problem Statement
Write the code to provide validation for the ExamResult class. The solution must meet the following requirements (new requirements are in bold):
- Should get the name, student Id, total marks, and exam weight
- Should get and set the marks earned
- Should override the toString() to show “The student (studentId) received earnedMarks/totalMarks for this examName exam.”
- Should require the total marks and weight to be a positive, non-zero value
- Should not allow a weight over 50
- The marks earned must be between zero and the total possible marks, inclusive
- The student ID must be nine digits
- The exam name cannot be an empty string (and must be trimmed)
LabResult
Requires a positive, non-zero value for the lab number, total marks and weight. The weight cannot be over 50. The marks earned can be between zero and the total marks, inclusive. The student ID must be 9 digits.
Problem Statement
Write the code to provide validation for the LabResult class. The solution must meet the following requirements (new requirements are in bold):
- Should get the lab number, student Id, total marks, and lab weight
- Should get and set the marks earned
- Should override the toString() to show “The student (studentId) received earnedMarks/totalMarks for this lab.”
- Should require the total marks and weight to be a positive, non-zero value
- Should not allow a weight over 50
- The marks earned must be between zero and the total possible marks, inclusive
- The student ID must be nine digits
- The lab number must be a positive number
### PeopleCounter
Does not allow adding a negative number of people to the counter.
Problem Statement
Write the code needed to track people entering and leaving a store. It must be able to estimate the number of people that have entered the store at the end of the day. The solution must meet the following requirements (new requirements are in bold):
- Should default to having a count of zero people when first started up
- Should increment by one (that is, count a single person)
- Should increment by a specified quantity (for when a group of people enter)
- Should adequately estimate the number of people who entered the store, assuming that each person who enters also leaves the store
Each estimate should be rounded down; for example, if 15 people are counted, then the estimate should be for only 7 (not 7.5 or 8) - Should not allow a zero or negative quantity when adding to the counter
Use the following class diagram when creating your solution.
BulkItem
The description cannot be blank and the cost and quantity values must be greater than zero.
Problem Statement
Write the code for the BulkItem class. The solution must meet the following requirements (new requirements are in bold):
- Should get and set the cost and quantity of the bulk item
- Should get and set the description
- Should ensure the description is not empty (and that it is trimmed)
- Should ensure the cost and quantity values are greater than zero
- Should calculate the cost for each item in the bulk item
- Should properly round values for currency (either the US or Canadian dollar)
Use the following class diagram when creating your solution.