• Register
1 vote
17 views

Problem:

I am new to the programming world. Just started learning with Java. I know my question is the very basic level. But, yeah I do want to know, how can I square a number in Java?

Best regards

12 7 7
15,250 points

1 Answer

1 vote

Solution:

Welcome mate.

Let’s come to the point. You can square a number in a couple of ways. The easiest way to square a number is multiplying with itself.  Another way is to call a method named math.pow 

Let’s see how to do it using math.pow

import java.util.*;
public class Square{

  public static void main(String args[]){

  Scanner sc=new Scanner(System.in);
  int number;
  System.out.print("Enter a number: ");
  num=sc.nextInt();
  System.out.println("Square of "+ number + " is: "+ Math.pow(number, 2));

  }

}

Using a method where we will multiply the number with itself

import java.util.Scanner;
public class SquareNum{

  public static void main(String [] args){

  Scanner sc = new Scanner(System.in);
  System.out.print("Please enter a number: ");
  int num = sc.nextInt();
  System.out.println("Your squared number is: " + square(num));

  }

//Here is our method to get the square

public static int square(int num){

  return num * num;

  }

} 

I hope this will help you to understand better. Keep coding  cool

13 9 6
94,240 points

Related questions

0 votes
1 answer 2 views
2 views
I need to check if a number is a perfect squre in java.
asked Oct 5 Daniel Anderson 4k points
0 votes
1 answer 6 views
2 votes
1 answer 7 views
7 views
Problem: Hello all, I am a secondary school level student and recently started learning Java programming out my curiosity. I have got a textbook on Java programming. I just completed the chapter of for-loop and continue solving the exercises of this chapter. I have got weird a ... you guys. But, yeah it is important to know for me. Thanks for being nice to me. I must recognize your help. Thanks.
asked Apr 12 Gavin 15.3k points
1 vote
1 answer 17 views
17 views
Problem: Folks, I hope you are doing well. I started learning java programming very recently. I am on the chapter of Data Type right now of the book from where I am taking the help. There is a problem give in my book’s exercise that: “if you want to ... . Is it really possible to do so? If so, then how? Could you please give a hint regarding the problem given above? Best regards.
asked Mar 17 Gavin 15.3k points
0 votes
1 answer 17 views
17 views
I was doing my java programming practice. I wrote a code to check if a charcter is a number: public static void main(String[] args) { String string = "-1234.15"; String numeric ; numeric = string.matches("-?\\d+(\\.\\d+)?"); if(numeric) System.out.println(string + " is a number"); else System.out.println(string + " is not a number"); } But it gives me error. Whats wrong in my code?
asked Mar 15 LizzyM 6.1k points