The volume of a cube with side s
is: s x s x s
or s
to the 3rd power.
In Java, the Math.pow(x,y)
function raises x
to the power y
. Both variables are double values, and the function returns a double result.
Letβs write a Java program to calculate the volume of a cube. The first three lines import the Scanner
class (needed for user input), declare the Java program class, and declare the main method:
import java.util.Scanner;
public class Volume {
public static void main(String[] args) {
Declare two variables in the main method to store the side of the cube and the volume:
double s; // side
double v; // volume
Create a Scanner object that scans standard input. Store the object in the variable in:
Scanner in = new Scanner(System.in);
Ask the user to input a value for the side:
System.out.println("Please enter the side of the cube: ");
Use the nextDouble()
method of the Scanner object to accept the side from the user and store it in the variable s
. Note that the program will wait on this line until the user presses the Enter key to input a value:
s = in.nextDouble();
Use the Math.pow()
function to raise s
to the power 3
. Store the result in the variable v
:
v = Math.pow(s,3);
Output the result:
System.out.println("The volume of cube with side " + s + " is " + v + ".");
Finally, close the main method and Java program:
}
}
Here is the complete program:
import java.util.Scanner;
public class Volume {
public static void main(String[] args) {
double s; // side
double v; // volume
Scanner in = new Scanner(System.in);
System.out.println("Please enter the side of the cube: ");
s = in.nextDouble();
v = Math.pow(s,3);
System.out.println("The volume of cube with side " + s + " is " + v + ".");
}
}
Thanks for reading. π
Follow me on Twitter @realEdwinTorres
for more programming tips and help.
Top comments (1)
π Ready for a coding challenge? Areon Network invites you to its Hackathon! Head to hackathon.areon.network to register and compete for a share of the $500,000 prize pool. Code, innovate, and win! π»π° #AreonHackathon #TechInnovation