PLEASE HELP WITH C Question When setting the dimensions of a
PLEASE HELP WITH C++!!
Question:
When setting the dimensions of a geometric object, the lengths of the sides should be positive values. Write a program that repeatedly asks for the dimensions of a rectangle and displays the area. Before an error is presented, collected both the length and the width values in a new class called Rectangle.
Create a class DimError, that is used by the new Rectangle class. The following methods must be defined for the Rectangle object:
void Rectangle::setWidth(int width);
void Rectangle::setLength(int length);
If either setWidth or setLength is called with a negative value it throws a DimError that includes a message indicating which method was called and the reason for the error. Use the main function defined below to produce the output that follows
main:
int main(void) {
Rectangle r;
try {
while (true) {
int l, w;
cout << \"Enter a length: \";
cin >> l;
cout << \"Enter a width: \";
cin >> w;
r.setLength(l);
r.setWidth(w);
cout << \"The area is: \" << r.area() << endl;
}
} catch (DimError de) {
cout << \"Couldn\'t set the rectangle\'s dimensions: \" << endl
<< de.what() << endl;
}
cout << \"Exiting...\" << endl;
return 0;
}
output:
Enter a length: 5
Enter a width: 10
The area is: 50
Enter a length: 3
Enter a width: 3
The area is: 9
Enter a length: -3
Enter a width: 5
Couldn\'t set the rectangle\'s dimensions:
setLength called with a negative length.
Exiting...
Press any key to continue . . .
Solution
#include <iostream>
/* run this program using the console pauser or add your own getch, system(\"pause\") or input loop */
using namespace std;
class DimError{
public:
void what(){
cout <<\"\ Negative values are not allowed:\ \" ;
}
};
class Rectangle{
private:
int length,width;
public:
void setLength(int length){
if(length >=0){
this->length =length;
}
else{
DimError d;
d.what();
exit(0);
}
}
void setWidth(int width){
if(width >=0){
this->width =width;
}
else{
DimError d;
d.what();
exit(0);
}
}
void area(){
cout << (width*length) << \"\ \";
}
};
int main(int argc, char** argv) {
Rectangle r;
try {
while (true) {
int l, w;
cout << \"Enter a length: \";
cin >> l;
cout << \"Enter a width: \";
cin >> w;
r.setLength(l);
r.setWidth(w);
cout << \"The area is: \";
r.area();
}
}
catch (DimError de) {
cout << \"Couldn\'t set the rectangle\'s dimensions: \" << endl;
de.what();
}
cout << \"Exiting...\" << endl;
return 0;
}


