Note: Programming Exercise #14_2: As discussed in the lecture note, the following produces NaN (short for not a number)
Posted: Sat May 14, 2022 7:21 pm
Note: Programming Exercise #14_2: As discussed in the lecture note, the following produces NaN (short for not a number) as output due to lack of mechanism to find the “squared root of a negative number”, and it can be considered an exception. System.out.print (Math.sqrt(-5)); Instruction: 1. Use Notepad to create new text file named “EX14_2.java”. Enter the following two lines (be sure to replace YourFullName with your full name): // FileName: EX14_2.java // Programmer: Your FullName 2. Next to the above two lines, 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”. 3. 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. 4. If n is a positive number or zero, display the result of Math.sqrt(n). 5. 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