Issue
I'm currently in the process of learning Java and I have been given a task to re-write my program. My program at the moment consists of a method called: calculateArea() which is used to calculate 3 different shapes area (a Rectangle, Circle and a Square).
I now need it to accept user input to choose one of the three shapes, for it to accept user input for the parameters (length and width) and for it to then calculate it and after printing the correct result, to close the program.
I already created setters and getters for the different shapes and tested that everything works, what I struggle with is how to implement the Scanner to accept the different Shape inputs.
I tried a simple Scanner input for now like this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter shape to calculate: ");
String shape = keyboard.nextLine();
shape = String.valueOf(rectangle.calculateArea());
System.out.println("Your chosen shapes area is: " + shape);
Though this way, it always calculates Rectangles values as I'm directly calling the method on Rectangle. How would I need to re-write it, for it to take the shape + parameters and then print out the value of said input?
I'm still very new and I don't know how to tackle issues/research like this to find out the right answer, so I would appreciate pointers.
Solution
Assuming you have a class per shape like
class Rectangle {
private double height;
private double width;
public Rectangle(double height, double width) {
this.height = height;
this.width = width;
}
public double calculateArea() {
return height * width;
}
}
and
class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double calculateArea() {
return radius * radius * 3.1415;
}
}
what you could do is depending on a value of shape
String
that you get from keyboard
Scanner
to instantiate a class corresponding to the shape and call its calculateArea()
method, e.g.,
String shape = keyboard.next();
if ("rectangle".equals(shape)) {
System.out.println(new Rectangle(keyboard.nextDouble(), keyboard.nextDouble()).calculateArea());
} else if ("circle".equals(shape)) {
System.out.println(new Circle(keyboard.nextDouble()).calculateArea());
} else {
System.out.println("unknown shape, known shapes are rectangle and circle");
}
Answered By - ouid
Answer Checked By - Cary Denson (JavaFixing Admin)