DEV Community

Edwin Torres
Edwin Torres

Posted on

Calculate the Volume of a Cube in Java

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) {
Enter fullscreen mode Exit fullscreen mode

Declare two variables in the main method to store the side of the cube and the volume:

double s;  // side
double v;  // volume
Enter fullscreen mode Exit fullscreen mode

Create a Scanner object that scans standard input. Store the object in the variable in:

Scanner in = new Scanner(System.in);
Enter fullscreen mode Exit fullscreen mode

Ask the user to input a value for the side:

System.out.println("Please enter the side of the cube: ");
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Use the Math.pow() function to raise s to the power 3. Store the result in the variable v:

v = Math.pow(s,3);
Enter fullscreen mode Exit fullscreen mode

Output the result:

System.out.println("The volume of cube with side " + s + " is " + v + ".");
Enter fullscreen mode Exit fullscreen mode

Finally, close the main method and Java program:

  }
}
Enter fullscreen mode Exit fullscreen mode

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 + ".");
  }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading. πŸ˜ƒ

Follow me on Twitter @realEdwinTorres for more programming tips and help.

Latest comments (1)

Collapse
 
kashton51 profile image
kashton | Areon

πŸŽ‰ 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