This a Java program designed to calculate both the square and cube of a number entered by the user.
It provides a quick and convenient way to obtain the square (n^2) and cube (n^3) values of any numeric input.
In this program:
- Importing Required Libraries: The program starts by importing the necessary library java.util.Scanner to allow user input.
- Variable Declarations: It declares three integer variables: n, square, and cube.
- n will store the number entered by the user.
- square will store the square (n^2) of the input.
- cube will store the cube (n^3) of the input.
- Creating a Scanner Object: The program creates a Scanner object named scanner to read input from the user.
- User Input: The program prompts the user to enter a number by displaying the message "Enter Number: ". It waits for the user to input an integer, which is then read and stored in the n variable using scanner.nextInt().
- Closing the Scanner: After obtaining the user's input, the program closes the Scanner object using scanner.close() to release the resources associated with it.
- Calculating Square and Cube: The program calculates the square of the entered number by multiplying n by itself and stores it in the square variable. Similarly, it calculates the cube of the number by multiplying n by itself twice and stores it in the cube variable.
- Displaying Results: Finally, the program displays the results. It prints the square value with the message "Square: " and the cube value with the message "Cube: ". The calculated square and cube values are shown on separate lines for clarity.
import java.util.Scanner;
public class SquareAndCube {
public static void main(String[] args) {
int n, square, cube;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Number: ");
n = scanner.nextInt();
scanner.close();
square = n * n;
cube = n * n * n;
System.out.println("\nSquare: " + square);
System.out.println("Cube: " + cube);
}
}
Follow Us