Skip to content

Instantly share code, notes, and snippets.

@ShubhamShakyawal
Last active November 8, 2018 10:57
Show Gist options
  • Save ShubhamShakyawal/befedf923773d4e84cf6d706e183e4c5 to your computer and use it in GitHub Desktop.
Save ShubhamShakyawal/befedf923773d4e84cf6d706e183e4c5 to your computer and use it in GitHub Desktop.
Square root method in java
import java.util.Scanner;
public class SquareRoot {
public static void main(String[] args) {
String input;
double sqrt,
roundoff; //Declaring Variable
System.out.println("To find Square Root"); //To print title Sq. root
System.out.println("Enter a Number : "); //Asking user input
Scanner keyboardInput = new Scanner(System. in ); //to get input
input = keyboardInput.nextLine(); // Getting value in variable
try {
// checking valid integer using parseInt() method
int number = Integer.parseInt(input);
if (number >= 0) // To display Output
{
sqrt = Math.sqrt(number);
roundoff = Math.round(sqrt * 100.0) / 100.0;
System.out.println("Square root = " + roundoff);
}
else {
System.out.println("Wrong Input! \n" + input + " is not a valid integer number ");
}
}
catch(NumberFormatException e) {
System.out.println("Wrong Input! \n" + input + " is not a valid integer number ");
}
}
}
@ShubhamShakyawal
Copy link
Author

The above square root method can find the sq. root of a number and if there is any wrong input (other than numeric value) it will show an error message

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment