Answer to Question #194030 in Java | JSP | JSF for Bill

Question #194030

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 


1
Expert's answer
2021-05-18T02:54:53-0400
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");
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS