logo

Rectangle Class in Java

   

Added on  2023-04-12

7 Pages1167 Words75 Views
Part 1
import javax.swing.JOptionPane;
/* Initial Rectangle Class */
public class Rectangle {
private float length, width; // define the variables for the
dimensions
public Rectangle ()
{
length = 1; //* Variable initialised to 1
width =1;
}
public float area () // calculate the area
{
float area = (length * width);
return area;
/* JOptionPane.showMessageDialog(null, "Area of the Rectangle
is "+ area);*/ //* get the area of the rectangle
}
public float perimeter () //calculate the perimeter
{
float perimeter; //perimeter variable
perimeter = (2* length) + (2 * width);
return perimeter;
/* JOptionPane.showMessageDialog(null, "perimeter of the
rectangle is " + perimeter); */ //* display the perimeter of the rectangle
}

public Rectangle (float l, float w) //set the length and width of the
rectangle
{
length = ((l > 0.0 && l <20.0) ? l:(float) 0.0); // validate
the dimensions of the length and width, set to 0 if outside defined ranges
width = ((w > 0.0 && w < 20.0) ? w:(float) 0.0);
}
public float getlength () //get length
{
return length;
}
public float getwidth () //get width
{
return width;
}
public String toString () //set values into a string format so they
can be called
{
if (length ==0 || width ==0 ) //check errors, if length / width
entered are 0 display error message.
{
return ("Incorrect information has been submitted. Please re assess
the values of length and width");
}
else
{
return String.format( "%s: %f\n%s: %f\n%s: %f\n%s: %f", /*
string format to output the required data */
"Length", length, "Width", width,
"Perimeter", perimeter(), "Area", area() );
}
}
}
Part 2
import javax.swing.JOptionPane;

public class RectangleTest {
public static void main(String[] args) {
Rectangle myR1 = new Rectangle(); //check default rectangle 1
Rectangle myR2 = new Rectangle ((float) 5.0, (float) 6.0);
//check integer types rectangle 2
Rectangle myR3 = new Rectangle ((float) 12.23, (float) 11.11);
//check float types rectangle 3
Rectangle myR4 = new Rectangle ((float) 21, (float) 19.999);
//check error handling rectangle 4
System.out.println("Information for Rectangle 1 \n" +
myR1.toString());
System.out.println("\nInformation for Rectangle 2 \n" +
myR2.toString());
System.out.println("\nInformation for Rectangle 3 \n" +
myR3.toString());
System.out.println("\nInformation for Rectangle 4 \n"
+myR4.toString());
}
}
Part 3 Cartesian Rectangle
import javax.swing.JOptionPane;
/* Initial Rectangle Class */
public class Rectangle {
// declare the variables
private float x1, y1;
private float x2, y2;
private float x3, y3;
private float x4, y4;
public Rectangle() //set the initial dimensions
{
setDimension( 1, 1, 5, 1, 5, 4, 1, 4 );
}

End of preview

Want to access all the pages? Upload your documents or become a member.

Related Documents
Rectangle Class Code
|12
|1173
|295

Workshop 2 CT619
|11
|1306
|421

Object Oriented Programming using Java
|14
|585
|389