Ryan H
Ryan H

Reputation: 85

Java making maths methods

I'm creating some method which do simple maths calculations. I have a square, cube and hypercube method. And I'm trying to create a power method which when n = 2, calls the square method, when n = 3, calls the cube method etc. I want this power method to return an int k. However the value of k doesn't seem to be travelling behond the if statements. Any suggestions?

  public int power(int x, int n){
    int k;
    if (n==2){
        k = square(x);
    }
    else if (n==3){
        k = cube(x);
    }
    else if (n==4){
        k = hypercube(x);
    }
    else if (n==1){
        k = x;
    }
    return k;
}

Upvotes: 0

Views: 110

Answers (4)

Kai Sternad
Kai Sternad

Reputation: 22830

k will be "known" by the end of the method if it was assigned along the way. Perhaps you enforce that no invalid value of k can be passed in, then it should do what you want it to do:

public int power(int x, int n){
    if (n < 1 || n > 4){
        throw new IllegalArgumentException("n is invalid :" + n);
    }
    int k = 0;
    if (n==2){
        k = square(x);
    }
    else if (n==3){
        k = cube(x);
    }
    else if (n==4){
        k = hypercube(x);
    }
    else if (n==1){
        k = x;
    }
    return k;
}

You should also make sure that x is always valid.

Upvotes: 0

Tim S.
Tim S.

Reputation: 56536

With your code, I get from the compiler "error: variable k might not have been initialized". I'm guessing this is what you mean. This is because, like the error suggests, if n isn't in the range 1 - 4, k is never explicitly set to any value. Here's one way to fix the problem, which allows the method to work for larger values of n (as long as you don't loop past Integer.MAX_VALUE):

public int power(int x, int n){
    int k;
    if (n==2){
        k = square(x);
    }
    else if (n==3){
        k = cube(x);
    }
    else if (n==4){
        k = hypercube(x);
    }
    else if (n==1){
        k = x;
    }
    else {
        k = 1;
        for (int i = 0; i < n; i++) {
            k *= x;
        }
    }
    return k;
}

Upvotes: 1

user1339772
user1339772

Reputation: 803

This code does not compile since k has not been initialized and you get compilation error at return k;. if you want to initialize with 0, use int k=0 in the declaration

Upvotes: 0

MightyPork
MightyPork

Reputation: 18861

You can use a loop for this, like here (I hope I got it right).

public int power(int x, int n){
    if(n==0) return 1;
    int k = x;
    while(--n > 0) {
        k *= x;
    }
    return k;
}

You might also add support for negative powers, but then you'd need some other return type (eg. float or double).

But honestly, why don't you just use Math.pow()?

Upvotes: 0

Related Questions