0
How do I write a try-throw catch exception to find the square root of the number input from scanner and use exception for -ve no
try-throw catch block if the number enter from the scanner is -ve number and check it using try-throw catch exception
1 ответ
+ 1
try-throw?
What like:
try{
throw new Exception();
}
?
Do you happen to mean a Try catch? Throw is not the same.
It would be helpful to tag the language you are referring to, 'Java'.
So, first you need to check if the input is a number.
Since you want to use a try catch, I assume the method you want to use is some type of convertion.
Example/
(Assume scanner is named sc)
try{
int input = Integer.parseInt(sc.next());
}
catch(InputMisMatchException e){
// was not a number
}
Then, you can take the sqrt of the number.
If you don't want to define your own sqrt method, you can use the one in the math class.
Example extended/
try{
double rootInput = Math.sqrt(Integer.parseInt(sc.next()));
// sqrt of input
// deal with this however you want to
if(Double.isNaN(rootInput))
{
// Negative root
}
}
catch(InputMisMatchException e)
{
// Failed to Cast (Not an int)
}