Reputation: 5
In my class, we have an assignment where we calculate the the volume and surface area of a cube. However, we can only use one instance field. Here's what I have so far...
The first thing was create a class for the cube, as show below.
public class cube{
//instance fields
private int sideLength;
//constructors
public cube() {
}
public cube(int height, int length, int width){
height=sideLength;
length=sideLength;
width=sideLength;
}
//methods
public int sideLength(){
return sideLength;
}
public void surfaceArea(){
int surfaceArea = (sideLength * sideLength) * 6;
}
public void volume(){
int volume = sideLength * sideLength * sideLength;
}
public String toString(){
return "cube[Side Length = "+sideLength+", Volume = , Surface area =]";
}
}
Where I am having the most amount of trouble is figuring out the toString method. I have to get the values that I've calculated from the volume
and surfaceArea
methods.
Currently, the code in the tester class would look like this
public class cubeTester{
public static void main (String[] args){
cube cube1 = new cube(6, 6, 6);
cube1.volume();
cube1.surfaceArea();
// From here on I have clue what to do
So, I'm not even sure if I'm creating the cube correctly, but I need to be able to eventually do something like this: System.out.println(cube1.toString());
, where the output would be like Cube[Side Length = 6, Volume = 216, Surface Area = 216]
. However, I'm stuck with trying to actually get the values back from the void methods. Can I have any help with this? Thank you.
Edit: The full requirements for the assignment are as follows; cube class should contain a default constructor, a constructor that takes in an integer side value, a get method, a method to calculatte the volume, a method to calculate the surface area, and a toString method. The class should contain only one instance field.
I must also create a test file that constructs a cube and contains a method call for all of the methods in the class.
Upvotes: 0
Views: 549
Reputation: 151
You can change the functions to return int instead of void like this:
public int surfaceArea(){
return ((sideLength * sideLength) * 6);
}
public int volume(){
return (sideLength * sideLength * sideLength);
}
Then, you can write the toString() function like this:
public String toString(){
return "cube[Side Length = " + sideLength + ", Volume = " + volume() + ", Surface area = " + surfaceArea() + "]";
}
Upvotes: 2
Reputation: 415
First of all you need to fix your surfaceArea() and volume() method. It should only return the calculated result.
Then in your toString() method, call those two methods to get the volume and area.
In your main method use
System.out.println(cube1);
to call the toString method. The above line is equivalent to
System.out.println(cube1.toString());
Upvotes: 0