Write a program (without imports) that prompts the user to enter a do.docx
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 x side length x side length), another
method to compute and return the volume (side length x side
length x 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.
Solution
public class Example {
/**
* @param args
*/
public static void main(String[] args) {
java.util.Scanner scanner = null;
try {
scanner = new java.util.Scanner(System.in);
System.out.print("Enter the side of cube :");
double sideLength = scanner.nextDouble();
System.out.println("Surface area of cube :" +
cubeArea(sideLength));
System.out.println("Volume of cube :" +
cubeVolume(sideLength));
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("Invalid Input");
} catch (IllegalArgumentException e) {
// TODO: handle exception
System.out.println("Invalid must be positive");
}
}
/**
* method to return surface area of cube
*
* @param sideLength
* @return
*/
public static double cubeArea(double sideLength) {
if (sideLength < 0) {
throw new IllegalArgumentException();
} else {
return (6 * sideLength * sideLength);
}
}
/**
* method to return volume of cube
*
* @param sideLength
* @return
*/
public static double cubeVolume(double sideLength) {
if (sideLength < 0) {
throw new IllegalArgumentException();
} else {
return (sideLength * sideLength * sideLength);
}
}
}
OUTPUT:
Enter the side of cube :3
Surface area of cube :54.0
Volume of cube :27.0