Question
I need the program to prompt the user to continue to enter values whether the value they entered is positive or negative. Right now I
I need the program to prompt the user to continue to enter values whether the value they entered is positive or negative. Right now I can't get the program to run after entering a value whether it is negative or not. I need to keep the part of the program where if you enter a negative number it prints out IllegalArgumentException and shows where the error occurs. I need to prompt the user when the program is first run to enter a number.
import java.util.Scanner;
public class sqrt
{
public static double sqrt(int number) throws IllegalArgumentException
{
double perm_dev = 0.0001;
double prevguess=1, next_guess=1;
if(number<0)
throw new IllegalArgumentException("Negative Number");
do
{
prevguess=next_guess;
next_guess=(prevguess + (number/prevguess))/2;
}
while(Math.abs(next_guess - prevguess)>perm_dev);
return next_guess;
}
//main method
public static void main(String args[])
{
//scanner object creation
Scanner sc = new Scanner(System.in);
//scanning input
int num=sc.nextInt();
//checking num greater than 0 or not and throwing exception if it's not zero
if (num < 0)
{
throw new IllegalArgumentException(Integer.toString(num));
}
//else calling the sqrt function and printing the value
else
{
double val=sqrt(num);
System.out.println(val);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started