I'm fairly new to Java and coding, but up until this point in the Java material, I haven't ran into any problems. What I really can't wrap my head around is how classes and methods actually work. I've been attempting to implement this over the last several hours to no avail:
Implement the class called Cylinder shown in UML below. The constructor accepts and initializes the radius and height for the Cylinder, while accessors and mutators allow them to be changed after object construction. The class also include methods that calculate and return the volume and surface area of the Cylinder. Lastly, it contains a toString method that returns the name of the shape, its radius, and its height. Create a main method which instantiates 4 Cylinder objects (any parameters), display them with toString()
, change one parameter (your choice) in each, and display them again.
UML:
This is the code that I currently have:
class Cylinder {
private double radius;
private double height;
// Method #1
private void rad (){
}
// Constructor
public Cylinder (double radius, double height){
this.radius = radius;
this.height = height;
}
// Method #2 for calculating volume.
double calcVolume (){
double volume = Math.PI * Math.pow(radius, 2) * height;
return volume;
}
// Method #3 for calculating surface area.
double calcArea (){
double area = (2 * Math.PI * radius * height) + (2 * Math.PI * Math.pow(radius, 2));
return area;
}
// toString method.
public String toString (){
StringBuilder sb = new Stringbuilder();
sb.append(radius).append(height);
return sb.toString();
}
}
public class Murray_A03Q1 {
public static void main(String[] args) {
Cylinder cylinder1 = new Cylinder(5, "can");
System.out.println(cylinder1);
Cylinder cylinder2 = new Cylinder(6, "cup");
Cylinder cylinder3 = new Cylinder(7, "jar");
Cylinder cylinder4 = new Cylinder(8, "paper roll");
}
}
What I really don't understand is how to use the 'get' and 'set' methods. Additionally, I'm not completely sure how to implement the toString method.
The following errors that I can't figure out how to correct are:
The constructor
Cylinder()
is undefined for - Cylindercylinder1 = new Cylinder();
Stringbuilder can't be resolved to a type for - StringBuilder
sb = new Stringbuilder();
Thank you for your help!