Site icon TestingDocs.com

Cube of a Number Java Program

Overview

In this tutorial, we will develop a Java Program to compute Cube of a Number. The program should prompt the user to input the number. The simplest way to compute the cube of a number is:

output= n*n*n;

Math.pow()

However, in Java we can leverage the Math class helper static methods. We cannot instantiate the Math class, nut we can invoke static methods of this class.For the sake of this example, we can use the pow() method.

This method returns the result of the value of the first parameter raised to the power of second parameter. To compute cube the second argument for the method should be three.

Example usage: Math.pow(n,3)

Things we need:

Machine with JDK Installed on it: Windows, Linux, Mac etc

IDE like Eclipse, IntelliJ, NetBeans IDE etc.

Java Program

/**
 * Sample Java Program to compute Cube of Number
 */
import java.util.Scanner;

/**
 * @author testingdocs.com
 */
public class CubeOfNumber {

	public static void main(String[] args) {
		Scanner keyBoard = new Scanner(System.in);
		System.out.print("Enter the number(n):= ");
//prompt user for number
		int n= keyBoard.nextInt();
		double output = Math.pow(n,3);//compute
		System.out.println("Cube of the number " + n 
+ " is := " + output);//display
	}
}

Sample Output

 

This program uses Scanner class to take input from the user. To import Scanner class, hover on the class name and select the java.util Scanner.

 

 

https://testingdocs.com/java-reading-from-standard-input/

Exit mobile version