In: Computer Science
Write the following program in java please.
a. Include a good comment when you write the method described below:
Method method1 receives an integer, n, and a real number, d, and returns a real number. If the integer is positive it returns the square root of the real number added to the integer. If the integer is negative or zero it returns the absolute value of the integer multiplied by the real number.
b. Write the statements from the main program to do each of the following:
1. Declare variables int1, an integer, and real1, a real number, and a variable result which willl store the value returned from the method.
2. Call the method method1 passing int1 and real1 as parameters, assigning the value returned to result.
3. Print with 4 decimal places the value returned from the method.
Java program:
import java.lang.Math;
import java.util.*;
class Test{
// Method method1 which receives an integer, and a real number, and returns a real number
public static double method1(int n,double d)
{
//if n is positive return square root of real number added with interger
if(n>0)
{
return Math.sqrt(d)+n;
}
// else if n is less then or equal to n return n*d
else {
return n*d;
}
}
public static void main(String args[])
{
int int1;
double real1;
double result;
Scanner sc=new Scanner(System.in);
// taking input for integer
System.out.print("Enter int1 : ");
int1= sc.nextInt();
//taking input for real number
System.out.print("Enter real1 : ");
real1= sc.nextDouble();
// calling method1 with int1 and real1
result=method1(int1,real1);
//printing the output
//String.format("%.4f",result) set the precision of result upto 4 decimal places
//if NaN is printed then it shows that result is not a real number
System.out.println("result : "+String.format("%.4f", result));
}
}
Note: if output is not a real number then NaN will be printed in place of output.
Test input and output: