I’m trying to write a program that prints the results of the exponents of the number 2 and I want to print it out 10 times. I want to create a a method that calculates the value of the exponents using the Math.pow(x,y) method.
2 to the power of 0 = 1
2 to the power of 1 = 2
2 to the power of 2 = 4
I have a couple of questions. Can you use the Math.pow method in a for loop like I did below? How do you declare the value of x and y in the method Math.pow(x, y) inside a for loop or do you have to do it outside a for loop? Also, in the raiseIntPower method in Eclipse when I use int n as a parameter it gives me a “duplicate local variable error.” My understanding is the method parameters specifies the argument the method requires. I don’t understand the meaning of that duplicate error.
import acm.program.*;
public class Exponents extends ConsoleProgram {
public void run(){
for (int n = 0; n <= 10; n++) {
println("2 to the power of " + n + " = " + raiseIntPower(n));
}
}
private int raiseIntPower (int n){
int total = 0;
for( int n = 0; n <= 10; n++){
total = Math.pow(2, n);
}
return total;
}
}
I dont understand what are you trying to do
just replace the statement
with
and it should do it , no need for
raiseIntPower()I think you are confused about the usage of
Math.pow(), please refer here for clarifications Math.pow()