I'm writing a method for integer power which is something like this 2^4 read in program like 2*2*2*2 without using the math class method. I tried to use several different ways to write, but I think can't figure out where I did wrong. I know I'm close to what it should look like, but something is wrong. Another question I have is I use the if state to specify if the power equal to 0, display 1, but when I enter 0 it display 0. What is the problem?
here is the code for the method
public class Power
{
public static int integerPower(int ba, int pow)
{
int base = ba;
int power = pow;
int x= 1;
if (base==1 || power==0 )
x=1;
else
{
for(int counter=0; counter < power; counter++ )
{
x *=base;
}
}
return x;
}
}
Here is the application I use to call the method. I think I did it correctly.
import java.util.Scanner;
public class PowerCalculate
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
System.out.print("Please enter the base: ");
int pow = input.nextInt();
System.out.print("Please enter the power: ");
int ba = input.nextInt();
System.out.println(Power.integerPower(ba, pow));
}
}
Thank you so much