This Java program calculates the volume and surface area of a cube given its edge length. The program defines two static methods, getVolume and getSurface, which compute the volume and surface area, respectively. The main method takes the edge length as input from the user and then calls these methods to display the results.
import java.util.Scanner;
public class VolumeAndSurfaceExample {
static double getVolume(double a) {
double volume;
volume = a * a * a;
return volume;
}
static double getSurface(double a) {
double surface;
surface = 6 * a * a;
return surface;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double edgeLength;
System.out.println("Please enter the edge length: ");
edgeLength = scan.nextInt();
scan.close();
System.out.println("Volume: " + getVolume(edgeLength));
System.out.println("Surface: " + getSurface(edgeLength));
}
}
Please enter the edge length:
5
Volume: 125.0
Surface: 150.0
static double getVolume(double a) {
double volume;
volume = a * a * a;
return volume;
}
The getVolume method calculates the volume of a cube.
a (double): The edge length of the cube.volume.static double getSurface(double a) {
double surface;
surface = 6 * a * a;
return surface;
}
The getSurface method calculates the surface area of a cube.
a (double): The edge length of the cube.surface.public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double edgeLength;
System.out.println("Please enter the edge length: ");
edgeLength = scan.nextInt();
scan.close();
System.out.println("Volume: " + getVolume(edgeLength));
System.out.println("Surface: " + getSurface(edgeLength));
}
The main method is the entry point of the program. It reads user input for the edge length of the cube, calculates the volume and surface area, and prints the results.
Scanner object to read input from the console.edgeLength to store the edge length of the cube.nextInt() method.Scanner object to free resources.getVolume method with edgeLength as argument and print the result.getSurface method with edgeLength as argument and print the result.