The challenge
Write a function that returns the total surface area and volume of a box as an array: [area, volume]
The solution in Java
We know that the formula to calculate the area of a box is as follows:
2(h × W) + 2(h × L) + 2(W × L)
We also know that the formula to calculate the volume of a box is as follows:
W x h x H
Therefore, we can write the following code:
public class SurfaceAreaAndVolume { public static int[] getSize(int w,int h,int d) { int area = ((h * w)*2) + ((h * d)*2) + ((w * d)*2); int volume = w*h*d; return new int[] {area, volume}; } }
Test cases to validate our code
It is important to have some tests to validate that our code works correctly with different inputs.
import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertArrayEquals; import org.junit.runners.JUnit4; public class FinalTest { @Test public void Test1() { assertArrayEquals(new int[] {88,48},SurfaceAreaAndVolume.getSize(4, 2, 6)); assertArrayEquals(new int[]{6,1}, SurfaceAreaAndVolume.getSize(1, 1, 1)); assertArrayEquals(new int[]{10,2}, SurfaceAreaAndVolume.getSize(1, 2, 1)); assertArrayEquals(new int[]{16,4}, SurfaceAreaAndVolume.getSize(1, 2, 2)); assertArrayEquals(new int[]{600,1000}, SurfaceAreaAndVolume.getSize(10, 10, 10)); } @Test public void RandomTest() { Rg rg = new Rg((int) 69 * 10000); int x = rg.a(); int y = rg.b(); int z = rg.c(); assertArrayEquals(Preloaded.getSize(x, y, z), SurfaceAreaAndVolume.getSize(x, y, z)); } }