Write a class called Rectangle (filename: Rectangle.java) that maintains two att
ID: 3685258 • Letter: W
Question
Write a class called Rectangle (filename: Rectangle.java) that maintains two attributes to represent the length and width of a rectangle. Provide suitable get, set, and toString methods plus two methods that return the perimeter and area of the rectangle. Include two constructors for this class. One a parameterless constructor that initializes both the length and width to 0, and the second one that takes two parameters to initialize the length and width. Write a java program (a driver application) that tests the above class by providing the users with the following menu options: 1 - to set the length 2 - to set the width 3 - to get the length 4 - to get the width 5 - to get the perimete r6 - to get the area 7 - to print the object as string 0 - to quit The program should create one Rectangle object at the beginning using the default constructor, and then repeatedly call the appropriate method for that object depending on the user selection from the above menu.
Explanation / Answer
import java.util.*;
public class RectangleTest{
public static void main(String []args){
Rectangle rect=new Rectangle();
System.out.println("Welcome to Rectangle Calculator");
Scanner read=new Scanner(System.in);
int choice,flag=1;
while(flag==1)
{
System.out.println(" Choices are");
System.out.println("1 - to set the length"+
" 2 - to set the width "+
" 3 - to get the length"+
" 4 - to get the width"+
" 5 - to get the perimeter"+
" 6 - to get the area" +
" 7 - to print the object as string" +
" 0 - to quit");
System.out.print(" Enter your choice: ");
choice=read.nextInt();
switch(choice)
{
case 0: System.exit(0);
flag=0;
break;
case 1: System.out.print("Enter length: ");
rect.setLength(read.nextInt());
break;
case 2: System.out.print("Enter width: ");
rect.setWidth(read.nextInt());
break;
case 3: System.out.print("Length of rectangle: "+rect.getLength());
break;
case 4: System.out.print("Width of rectangle: "+rect.getWidth());
break;
case 5: System.out.print("Permieter of rectangle: "+rect.calPerimeter());
break;
case 6: System.out.print("Area of rectangle: "+rect.calArea());
break;
case 7: System.out.print("Rectangle Specs :"+rect.toString());
break;
default:System.out.print("Invalid choice");
break;
}
}
}
}
class Rectangle
{
int width,length;
public Rectangle()
{
length=0;
width=0;
}
public Rectangle(int length,int width)
{
this.length=length;
this.width=width;
}
void setLength(int length)
{
this.length=length;
}
int getLength()
{
return this.length;
}
void setWidth(int width)
{
this.width=width;
}
int getWidth()
{
return this.width;
}
int calArea()
{
return length * width;
}
int calPerimeter()
{
return 2 *(length + width);
}
public String toString()
{
return "Length :"+length + " Width :"+width;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.