• Register
+3 votes
11 views

Problem:

Hello good soul,

I am a student of basic java programming. I was solving beginner-level problems from there. Right now I got a problem that says, write a program that squares an integer and prints the result.

Well, I am not one of those who always look solution for their assignment on StackOverflow or other sites. I just want to learn the process.

Thanks for your help.

ago by (5.9k points)  

1 Answer

+1 vote

Solution:

We can do it in several ways. Let me show you some ways, and then you decide which one is best for you.

import java.util.Scanner;
public class SquareNumber {
	private static Scanner roy;
	public static void main(String[] args) 
	{
		int num, sqr;
		roy = new Scanner(System.in);
		System.out.print(" Please Enter a Number : ");
		num = roy.nextInt();		
		sqr = num * num;
		System.out.println("The Square of the Given Number is: "+ square);
	}
}

This is the easiest way I think. You just need to prompt a number from the user and multiply with itself (basics of squaring a number).

Using a method:

import java.util.Scanner;
public class SquareNumber1{
	private static Scanner roy;
	public static void main(String[] args) 
	{
		int num, sqr;
		num = new Scanner(System.in);
		System.out.print("Please Enter a Number : ");
		num = roy.nextInt();	
		sqr = calsquare(num);
		System.out.println("The Square of the Given Number is: "+ square);
	}
	
	public static int calsquare(int number)
	{
		return number * number;
	}
}

We did the same thing in our last program but calling a method only. What we’ve done in our entire program (first one), the function calsquare() did the same in our last program.

import java.util.*;
public class SquareNumber {
	public static void main(String args[]){
		Scanner roy = new Scanner(System.in);
		int num;
		System.out.print("Enter an integer number: ");
		num=roy.nextInt();

		System.out.println("Square of "+ num + " is: "+ Math.pow(num, 2));
	}
}

This one is a pretty advance level. All you need to prompt a number and pass it through a built-in function Math.pow() to make it square. Keep in mind the parameters inside the function expressing the data type and executable power

Thanks

ago by (17.7k points)  
...