Write a program (without imports) that prompts the user to enter a double value.
ID: 3574855 • Letter: W
Question
Write a program (without imports) that prompts the user to enter a double value. This double represents the length of a side of a cube. The program has a method to compute and return the surface area of a cube (6 times side length times side length), another method to compute and return the volume (side length times side length times side length) and a main method to do the rest of the work (prompt the user, call the methods, display the results). Your area and volume methods should throw an exception if the argument (side length) is negative - this is an illegal argument. Your main method should catch this exception and any number format exception if the user tries to enter a String when prompted for the side length. The program should continue (prompt, compute, display) until the user enters a side length of 0 which ends the program.Explanation / Answer
import java.util.Scanner;
public class CubeAreaVolume {
public static void main(String[] args) {
Scanner scanner = null;
double length;
try {
scanner = new Scanner(System.in);
do {
System.out.print(" Enter the side length of cube:");
length = scanner.nextDouble();
try {
if (length < 0)
throw new IllegalArgumentException();
else if (length == 0)
break;
} catch (IllegalArgumentException e) {
// TODO: handle exception
System.out.println("Invalid cube length");
continue;
}
System.out.println("Area of Cube: " + computeArea(length));
System.out.println("Volume of Cube: " + computeVolume(length));
} while (true);
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* compute volume
*
* @param sideLength
* @return
*/
public static double computeVolume(double sideLength) {
return (6 * sideLength * sideLength);
}
/**
* compute area
*
* @param sideLength
* @return
*/
public static double computeArea(double sideLength) {
return (sideLength * sideLength * sideLength);
}
}
OUTPUT:
Enter the side length of cube:3
Area of Cube: 27.0
Volume of Cube: 54.0
Enter the side length of cube:4
Area of Cube: 64.0
Volume of Cube: 96.0
Enter the side length of cube:7
Area of Cube: 343.0
Volume of Cube: 294.0
Enter the side length of cube:-2
Invalid cube length
Enter the side length of cube:12
Area of Cube: 1728.0
Volume of Cube: 864.0
Enter the side length of cube:3.2
Area of Cube: 32.76800000000001
Volume of Cube: 61.44000000000001
Enter the side length of cube:0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.