Last active
November 8, 2018 10:57
-
-
Save ShubhamShakyawal/befedf923773d4e84cf6d706e183e4c5 to your computer and use it in GitHub Desktop.
Square root method in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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