I\'m working on multiple assignments for a Java class I am taking and have gotte
ID: 3559171 • Letter: I
Question
I'm working on multiple assignments for a Java class I am taking and have gotten stuck on both.. here is the sceond assignment I have to complete, I believe I have coded the program right but have gotten unfimilar errors and would like someone to please review it and fix it up for me.
Assignment:
Create a class Rectangle in a .java file. The class has member data: length and width (both are double type), each of which defaults to 1.0. Create a method that calculates the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each double numbers larger than 0.0 and less than 20.0. Don
Explanation / Answer
import java.text.DecimalFormat;
public class Rectangle {
private double length, width;
DecimalFormat df = new DecimalFormat("#.00");
// constructor without paramters
public Rectangle()
{
setLength( 1.0 );
setWidth( 1.0 );
}
// constructor with length and width supplied
public Rectangle( double theLength, double theWidth )
{
setLength( theLength );
setWidth( theWidth );
}
// validate and set length
public void setLength( double theLength )
{
length = ( theLength > 0.0 && theLength < 20.0 ? theLength : 1.0 );
}
// validate and set width
public void setWidth( double theWidth )
{
width = ( theWidth > 0 && theWidth < 20.0 ? theWidth : 1.0 );
}
// get value of length
public double getLength()
{
return length;
}
// get value of width
public double getWidth()
{
return width;
}
// calculate rectangle's perimeter
public double perimeter()
{
return 2 * length + 2 * width;
}
// calculate rectangle's area
public double area()
{
return length * width;
}
// convert to String
public String toRectangleString ()
{
return ( " Length: " + df.format(length) + " " + " Width: " + df.format(width) + " " +
" Perimeter: " + df.format(perimeter()) + " " + " Area: " + df.format(area()) );
}
public String toString()
{
return " Rectangle's Length: " + df.format(length) + " Width: " + df.format(width) +" Perimeter: " + df.format(perimeter()) + " Area: " + df.format(area());
}
}
//RectangleTest.java
import java.util.Scanner;
public class RectangleTest{
public static void main(String arhs[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter length of Rectangle : ");
double length = sc.nextDouble();
System.out.print("Enter width of Rectangle : ");
double width = sc.nextDouble();
Rectangle rect = new Rectangle(length,width);
System.out.println(rect.toRectangleString());
System.out.println(rect);
}
}
Output :
As Above You will get the Required Output