Write Java codes that use the “Scanner” class to ask the user to enter a number. Then, store the given number in a variable of double type named “n”. If n is a negative number, use the “throw” keyword to throw a message, “Java does not provide mechanism to find the squared root of a negative number...”. Then, use the “Exception” class to catch the thrown exception and display the message. If n is a positive number or zero, display the result of Math.sqrt(n).
Make sure the output looks similar to the following.
C:\test>java Sample
Enter a number: -5.1
Java does not provide mechanism to find the squared root of a negative number...
C:\test>java Sample
Enter a number: 5.1
2.2583179370125386
C:\test>java Sample
Enter a number: 0
0.0
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
System.out.print("n = ");
int n = new Scanner(System.in).nextInt();
try {
if (n >= 0)
System.out.println(Math.sqrt(n));
else
throw new Exception();
}
catch (Exception e)
{
System.out.println("Java does not provide mechanism to find the squared root of a negative number");
}
}
}
Comments
Leave a comment