1. Write a recursive function, power, that takes as parameters two integers x and y such that x is nozero and return xy. You can use the following recursive function definition to calculate xy.
If y>= 0,
1 if y=0
power(x, y) = x if y=1
x*power(x,y-1) if y>1
if y<0,
power(x, y) = 1/power(x, -y)
Write a TestPower class that call addRecur method. You should provide the user to enter integer to calculate its total. The method should throw an IllegalArgumentException if it is passed a value other than integer.
import java.util.*;
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
try {
System.out.print("Enter x: ");
String xString = keyBoard.nextLine();
int x = Integer.parseInt(xString);
System.out.print("Enter y: ");
String yString = keyBoard.nextLine();
int y = Integer.parseInt(yString);
try {
System.out.println(x + "^" + y + " = " + power(x, y));
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException");
}
} catch (NumberFormatException e) {
System.out.println("Not a valid integer values.");
}
keyBoard.close();
}
public static double power(int x, int y) throws IllegalArgumentException {
if (y == 0) {
return 1;
}
if (y < 0) {
return 1 / Math.pow((double) x, (double) -y);
}
return x * Math.pow((double) x, (double) (y - 1));
}
}
Comments
Leave a comment