Results 1 to 2 of 2
Thread: Rectangle Class
- 05-03-2012, 06:30 PM #1
Member
- Join Date
- Feb 2012
- Posts
- 5
- Rep Power
- 0
Rectangle Class
Create a class Rectangle. The class has attributes length and width, each of which defaults to 1. It has member functions that calculate the perimeter and the area of the rectangle. It has set and get functions for both length and width. The set functions should verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0.
Here is what I wrote.....
Java Code:public class Rectangle { import java.awt.Rectangle; class RectangleClass { float length=1; float width=1; public float getLength() { return length; } private float setLength(float length) { if ((length>0.0)&&(length<20.0)) { return length; } else { System.out.printf("Invalid length (%.2f) set to 1.\n",length); return (float)1; } } public float getWidth() { return width; } private float setWidth(float width) { if ((width>0.0)&&(width<20.0)) { return width; } else { System.out.printf("Invalid width (%.2f) set to 1.\n",width); return 1; } } public float calcPerimeter(float length, float width) { float perimeter=2 * (length + width); return perimeter; } public float calcArea(float length, float width) { float area= length * width; return area; } public static void main(String[] args) { Rectangle r=new Rectangle(); System.out.println("*** Test 1 - Valid length and width ***"); float l=r.setLength(5); float w=r.setWidth(2); float a=r.calcArea(l, w); float p=r.calcPerimeter(l, w); System.out.println("Area: "a"\nPerimeter: "+p); System.out.println(); // Test 2 - Invalid length and width System.out.println("*** Test 2 - Invalid length and width ***"); float l2=r.setLength(21); float w2=r.setWidth(-1); float a2=r.calcArea(l2, w2); float p2=r.calcPerimeter(l2, w2); System.out.println("Area: "a2"\nPerimeter: "+p2); } }
Also I would like to incoperate the extra credit but not sure how to do it.
(5 pts) Put the class Rectangle into the package com.deitel.ch08. Modify Assign8.java to import it.
(5 pts) Modify the set methods in Rectangle to return a boolean indicating whether the input is valid. The test program should keep prompting for input if it is invalid.
Any help in appreciated.
- 05-03-2012, 08:10 PM #2
Similar Threads
-
Rectangle class again
By toppcon in forum New To JavaReplies: 2Last Post: 05-05-2011, 04:25 AM -
Rectangle class with no argument constructor
By toppcon in forum New To JavaReplies: 1Last Post: 05-05-2011, 02:37 AM -
does rectangle contain or overlap another rectangle?
By Xycose in forum New To JavaReplies: 6Last Post: 12-01-2010, 12:29 AM -
Wrong with Rectangle res = new Rectangle(0,0,0,0);???
By jiapei100 in forum AWT / SwingReplies: 3Last Post: 09-25-2010, 04:39 PM -
help with rectangle class
By darkgt in forum New To JavaReplies: 7Last Post: 11-14-2007, 07:19 PM
Bookmarks