I need help writing this program in JAVA, this is an introductory java course, s
ID: 3811764 • Letter: I
Question
I need help writing this program in JAVA, this is an introductory java course, so if possible, keep it as basic/simple as possible while still following the instructions. The output should look like the sample execution at the end of the problem.
Write a program which asks the user to enter the length and width of a rectangle and computes the area. The program MUST include the following methods:
readLength: This method asks the user for the length of the rectangle, and returns the length.
readWidth: This method asks the user for the width of the rectangle and returns the width.
computeArea: This method takes the length and width as input and returns the computed area of the rectangle.
displaySolution: This method displays the solution to the problem.
You will need to think very carefully about how these methods should work together to find the solution.
Input Validation:
The length must be positive.
The width must be positive.
Requirements:
All four of the required methods must be implemented, and all must be correctly used within your program to get credit.
Explanation / Answer
// hope the program fulfills your requirements,feel free to comment for doubts or any modifications,All the best :)
import java.util.Scanner;
public class Rectangle {
public static double LENGTH;
public static double WIDTH;
public static void main(String args[])
{
double length = readLength();
double width = readWidth();
double area = computeArea(length, width);
System.out.println("Area of the rectangle="+area+" square units");
displaySolution();
}
public static double readLength(){
System.out.println("Enter the length :");
Scanner sc = new Scanner(System.in);
double length = sc.nextDouble();
if(length<0)
{
System.out.println("The length must be positive ");
length=readLength(); // you can remove this line and uncomment the line below to exit the program
// System.exit(1);
}
LENGTH=length;
return length;
}
public static double readWidth(){
System.out.println("Enter the width :");
Scanner sc = new Scanner(System.in);
double width = sc.nextDouble();
if(width<0)
{
System.out.println("The width must be positive ");
width=readWidth(); // you can remove this line and uncomment the line below to exit the program
// System.exit(1);
}
WIDTH=width;
return width;
}
public static double computeArea(double length,double width){
return length*width;
}
public static void displaySolution(){
System.out.println();
System.out.println("***********************SOLUTION***********************");
System.out.println("THE LENGTH IS :"+LENGTH+" units");
System.out.println("THE WIDTH IS :"+WIDTH+" units");
System.out.println("FORMULA: AREA of rectangle = LENGTH x WIDTH");
System.out.println("AREA of rectangle : "+LENGTH+" x "+WIDTH+" = "+computeArea(LENGTH, WIDTH)+" square units");
System.out.println("******************************************************");
}
}