Task: Write a Java Program To Input a Number and Display Its Square. The sample run of the required Java program is shown in the image below:
Stop Here, Please, Click to Read : Getting input from keyboard in Java, first
For getting input in a Java program, we may use the Scanner class. Please click on the above heading to read the complete input process step by step with images and the sample Java program.
The Source code of Java Program to input a number and calculate its square
/* This is Java Program to input a number from user through keyboard and display its square. */ package numsquare; /** * @author www.EasycodeBook.com */ // step 1 for keyboard input - // import Scanner class import java.util.Scanner; public class NumSquare { public static void main(String[] args) { int num, square; // step 2 for keyboard input // create an object let "keyboard" of Scanner class // by passing it System.in (standard system input device) Scanner keyboard = new Scanner(System.in); //Step 3 // Show message to enter data System.out.print("Enter a number to calculate square="); //Step 4 for keyboard input // call nextInt() method to initiate integer input num = keyboard.nextInt(); square = num * num; System.out.print("Square = " + square); } }
The Source code without comments of Java Program to find square of a number
package numsquare; import java.util.Scanner; public class NumSquare { public static void main(String[] args) { int num, square; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number to calculate square="); num = keyboard.nextInt(); square = num * num; System.out.print("Square = " + square); } }
Output and sample run of Java Square of number program
Pingback: Java Program To Check a Number is Prime or Composite » EasyCodeBook.com
Pingback: Write and Execute First Java Program in NetBeans » EasyCodeBook.com
Pingback: Get Keyboard Input in Basic Java Program | EasyCodeBook.com