Question: Create a Rectangle class with attributes 'length' and 'width', which default to the value Provide behaviors (ie. methods) that: -set width, -set length, -get length
Create a Rectangle class with attributes 'length' and 'width', which default to the value Provide behaviors (ie. methods) that:
-set width,
-set length,
-get length
-get width
-calculate perimeter,
-return the value of the perimeter,
-calculate area,
return the value of the area,
-toString()
-which outputs the Rectangles length,-
-width,
-perimeter, and area.
Be sure your 'set' methods validate user input (ie. must be a number greater than 0).
I'm having trouble having the program methods to recognize only numbers that are greater than 0.
// Definition of class Rectangle public class Rectangle { private double length; private double width; public Rectangle() { setLength( 1.0 ); setWidth( 1.0 ); } public Rectangle( double theLength, double theWidth ) { setLength( theLength ); setWidth( theWidth ); } public void setLength( double theLength ) { length = ( theLength > 0.0 && theLength < 20.0 ? theLength : 1.0 ); } public void setWidth( double theWidth ) { width = ( theWidth > 0 && theWidth < 20.0 ? theWidth : 1.0 ); } public double getLength() { return length; } public double getWidth() { return width; } public double perimeter() { return 2 * length + 2 * width; } public double area() { return length * width; } public String toString() { return String.format( "%s: %f %s: %f %s: %f %s: %f", "Length", length, "Width", width, "Perimeter", perimeter(), "Area", area() ); } } // end calss Rectangle
test code below:
// Exercise 8.4 Solution: RectangleTest.java // Program tests class Rectangle. import java.util.Scanner; public class RectangleTest { public static void main( String args[] ) { Scanner input = new Scanner( System.in ); Rectangle rectangle = new Rectangle(); int choice = getMenuChoice(); while ( choice != 3 ) { switch ( choice ) { case 1: System.out.print( "Enter length: " ); rectangle.setLength( input.nextDouble() ); break; case 2: System.out.print ( "Enter width: " ); rectangle.setWidth( input.nextDouble() ); break; } System.out.println ( rectangle.toString() ); choice = getMenuChoice(); } } private static int getMenuChoice() { Scanner input = new Scanner( System.in ); System.out.println( "1. Set Length" ); System.out.println( "2. Set Width" ); System.out.println( "3. Exit" ); System.out.print( "Choice: " ); return input.nextInt(); } } // end class RectangleTest
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
