Question

This exercise guides you through the process of converting an Area and Perimeter application from a...

This exercise guides you through the process of converting an Area and Perimeter application from a procedural application to an object-oriented application.
Create and use an object
1. Open the project named ch04_ex2_Area and Perimeter that’s stored in the ex_starts folder. Then, review the code for the Main class.
2. Create a class named Rectangle and store it in the murach.rectangle package.
3. In the Rectangle class, add instance variables for length and width. The, code the get and set methods for these instance variables. If possible, use your IDE to generate the get and set methods. With NetBeans, you can get started by selecting the RefactorEncapsulate Fields command.
4. Add a zero-argument constructor that initializes the length and width to 0.
5. Add a get method that calculates the area of the rectangle and returns a double value for the result. If you want, you can copy the code that performs this calculation from the Main class.
6. Add a get method that returns the area as a String object with standard numeric formatting and a minimum of three decimal places. To make it easy to refer to the NumberFormat class, you should add an import statement for it.
7. Repeat the previous two steps for the perimeter.
8. Open the Main class. Then, add code that creates a Rectangle object and sets its length and width.
9. Modify the code that displays the calculations so it uses the methods of the Rectangle object to get the area and perimeter of the rectangle.
10. Remove any leftover code from the Main class that’s unnecessary including any unnecessary import statements.
11. Run the application and test it with valid data. It should calculate the area and perimeter for a rectangle.
Overload the constructor
12. Open the Rectanble class. Then, overload the constructor by supplying a second constructor that accepts two arguments: length and width. This constructor should set the length and width of the rectangle to the values supplied by these arguments.
13. Open the Main class. Then, modify its code so it uses this constructor instead of the zero-argument constructor.
14. Run the application and test it to make sure it still works correctly.

----------------------

package murach.rectangle;

import java.text.NumberFormat;
import java.util.Scanner;

public class Main {

public static void main(String args[]) {
System.out.println("Welcome to the Area and Perimeter Calculator");
System.out.println();

Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get input from user
System.out.print("Enter length: ");
double length = Double.parseDouble(sc.nextLine());

System.out.print("Enter width: ");
double width = Double.parseDouble(sc.nextLine());

// calculate total
double area = width * length;
double perimeter = 2 * width + 2 * length;
  
// format and display output
NumberFormat number = NumberFormat.getNumberInstance();
number.setMinimumFractionDigits(3);
String message =
"Area: " + number.format(area) + "\n" +
"Perimeter: " + number.format(perimeter) + "\n";
System.out.println(message);

// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
System.out.println("Bye!");
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// Rectangle.java

package murach.rectangle;

import java.text.NumberFormat;

public class Rectangle {

              // attributes

              private double length;

              private double width;

              // default constructor, sets length and width to 0

              public Rectangle() {

                           length = 0;

                           width = 0;

              }

              // constructor taking arguments to initialize length and width

              public Rectangle(double length, double width) {

                           this.length = length;

                           this.width = width;

              }

              // getters and setters

              public double getLength() {

                           return length;

              }

              public void setLength(double length) {

                           this.length = length;

              }

              public double getWidth() {

                           return width;

              }

              public void setWidth(double width) {

                           this.width = width;

              }

              // method to calculate the area of rectangle

              public double getArea() {

                           return length * width;

              }

              // returns the area of rectangle as a labeled and formatted String

              public String getAreaString() {

                           NumberFormat number = NumberFormat.getNumberInstance();

                           number.setMinimumFractionDigits(3);

                           String str = "Area: " + number.format(getArea());

                           return str;

              }

             

              // method to calculate the perimeter of rectangle

              public double getPerimeter() {

                           return 2 * (length + width);

              }

              // returns the perimeter of rectangle as a labeled and formatted String

              public String getPerimeterString() {

                           NumberFormat number = NumberFormat.getNumberInstance();

                           number.setMinimumFractionDigits(3);

                           String str = "Perimeter: " + number.format(getPerimeter());

                           return str;

              }

}

//Main.java (updated)

package murach.rectangle;

import java.util.Scanner;

public class Main {

              public static void main(String args[]) {

                           System.out.println("Welcome to the Area and Perimeter Calculator");

                           System.out.println();

                           Scanner sc = new Scanner(System.in);

                           //creating an object of Rectangle

                           Rectangle rectangle=null;

                           String choice = "y";

                           while (choice.equalsIgnoreCase("y")) {

                                         // get input from user

                                         System.out.print("Enter length: ");

                                         double length = Double.parseDouble(sc.nextLine());

                                         System.out.print("Enter width: ");

                                         double width = Double.parseDouble(sc.nextLine());

                                        

                                         //creating a rectangle with entered length and width

                                         rectangle=new Rectangle(length, width);

                                         //displaying area and perimeter strings

                                         System.out.println(rectangle.getAreaString());

                                         System.out.println(rectangle.getPerimeterString());

                                         // see if the user wants to continue

                                         System.out.print("Continue? (y/n): ");

                                         choice = sc.nextLine();

                                         System.out.println();

                           }

                           System.out.println("Bye!");

              }

}

/*OUTPUT*/

Welcome to the Area and Perimeter Calculator

Enter length: 25.5

Enter width: 12.8

Area: 326.400

Perimeter: 76.600

Continue? (y/n): y

Enter length: 220.55

Enter width: 123.456

Area: 27,228.221

Perimeter: 688.012

Continue? (y/n): n

Bye!

Add a comment
Know the answer?
Add Answer to:
This exercise guides you through the process of converting an Area and Perimeter application from a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • java language Problem 3: Shape (10 points) (Software Design) Create an abstract class that represents a Shape and contains abstract method: area and perimeter. Create concrete classes: Circle, Rectang...

    java language Problem 3: Shape (10 points) (Software Design) Create an abstract class that represents a Shape and contains abstract method: area and perimeter. Create concrete classes: Circle, Rectangle, Triangle which extend the Shape class and implements the abstract methods. A circle has a radius, a rectangle has width and height, and a triangle has three sides. Software Architecture: The Shape class is the abstract super class and must be instantiated by one of its concrete subclasses: Circle, Rectangle, or...

  • ****Here is the assignment **** Purpose: To write an Object-Oriented application that creates a Java class...

    ****Here is the assignment **** Purpose: To write an Object-Oriented application that creates a Java class with several instance variables, a constructor to initialize the instance variables, several methods to access and update the instance variables’ values, along with other methods to perform calculations. Also, write a test class that instantiates the first class and tests the class’s constructor and methods. Details: Create a class called Rectangle containing the following: Two instance variables, An instance variable of type double used...

  • JAVA design a class named Rectangle to represent a rectangle. The class contains: A method named getPerimeter() that returns the perimeter. Two double data fields named width and height that specify...

    JAVA design a class named Rectangle to represent a rectangle. The class contains: A method named getPerimeter() that returns the perimeter. Two double data fields named width and height that specify the width and height of the rectangle. The default values are 1 for both width and height. A no-arg constructor that creates a default rectangle. A constructor that creates a rectangle with the specified width and height. A method named getArea() that returns the area of this rectangle. design...

  • Please, modify the code below to use the Switch Statements in Java instead of “if” statements...

    Please, modify the code below to use the Switch Statements in Java instead of “if” statements to make the decisions. import java.util.Scanner; public class Area { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter code(C for circle, R for rectangle, S for square): "); char code = in.next().charAt(0); if(code == 'C') { System.out.print("Enter radius: "); double radius = in.nextDouble(); System.out.println("Area of circle is " + (Math.PI * radius * radius)); } else if(code == 'R') {...

  • Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB....

    Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB. This interface should specify this abstract method: public abstract Product get(String productCode); Modify the ProductDB class so it implements the IProductDB interface. Write the code for the new ‘get’ method. Then remove the getProductByCode method. In the Main class, modify the code so it works with the new ProductDB class. This code should create an instance of the IProductDB interface like this: IProductDB db...

  • JAVA Modify the code to create a class called box, wherein you find the area. I...

    JAVA Modify the code to create a class called box, wherein you find the area. I have the code in rectangle and needs to change it to box. Here is my code. Rectangle.java public class Rectangle { private int length; private int width;       public void setRectangle(int length, int width) { this.length = length; this.width = width; } public int area() { return this.length * this.width; } } // CONSOLE / MAIN import java.awt.Rectangle; import java.util.Scanner; public class Console...

  • I am trying to write a Geometry.java program but Dr.Java is giving me errors and I...

    I am trying to write a Geometry.java program but Dr.Java is giving me errors and I dont know what I am doing wrong. import java.util.Scanner; /** This program demonstrates static methods */ public class Geometry { public static void main(String[] args) { int choice; // The user's choice double value = 0; // The method's return value char letter; // The user's Y or N decision double radius; // The radius of the circle double length; // The length of...

  • Why is my program returning 0 for the area of a triangle? public class GeometricObjects {...

    Why is my program returning 0 for the area of a triangle? public class GeometricObjects {    private String color = " white ";     private boolean filled;     private java.util.Date dateCreated;     public GeometricObjects() {         dateCreated = new java.util.Date();     }     public GeometricObjects(String color, boolean filled) {         dateCreated = new java.util.Date();         this.color = color;         this.filled = filled;     }     public String getColor() {         return color;     }     public void setColor(String color)...

  • Programming: Java: Fixing errors in code help: The errors are in square.java and rectangle.java and they...

    Programming: Java: Fixing errors in code help: The errors are in square.java and rectangle.java and they both say: constructor Shape in class Shape cannot be applied to given types; required: no arguments found: String reason: actual and formal argument lists differ in length The directions say: The files Shape.java and TestArea.java have been finished already, YOU DONT ADD ANYTHING TO THESE TWO. According to the requirement, you need to modify in Square.java and Rectangle.java, respectively a. Implementing constructor with no...

  • Project Objectives: To develop ability to write void and value returning methods and to call them...

    Project Objectives: To develop ability to write void and value returning methods and to call them -- Introduction: Methods are commonly used to break a problem down into small manageable pieces. A large task can be broken down into smaller tasks (methods) that contain the details of how to complete that small task. The larger problem is then solved by implementing the smaller tasks (calling the methods) in the correct order. This also allows for efficiencies, since the method can...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT