MasterMWF
MasterMWF

Reputation: 21

Java method using a for loop

I am learning Java and discovering that a little bit of knowledge is confusing. The goal is to write a method that is the equivalent of the n! function. I am using a for loop to multiply a variable declared outside the method. All I get back is 0.

What am I doing wrong?

//
// Complete the method to return the product of
// all the numbers 1 to the parameter n (inclusive)
// @ param n
// @ return n!

public class MathUtil
{
   public int total;

   public int product(int n)
  {
   for (int i = 1; i == n; i ++)
   {
       total = total * i;

    }
    return total;

  }
}

Upvotes: 0

Views: 7279

Answers (4)

Adrian Shum
Adrian Shum

Reputation: 40036

There is actually a lot of problems in your code:

  • It does not make sense to make it an instance method.
  • You have not initialize your total to a reasonable value.
  • The condition in your for loop is wrong
  • Method is not given a meaningful name
  • Messy indentation
  • (The list keeps growing...)

So here is a slightly improved version

public class MathUtil
{
  //
  // Complete the method to return the product of
  // all the numbers 1 to the parameter n (inclusive)
  // @ param n
  // @ return n!

  public static int factorial(int n)
  {
    int total = 1;
    for (int i = 1; i <= n; i ++)
    {
      total = total * i;
    }
    return total;
  }
}

so that you can call it as MathUtil.product(123) instead of some weird new MathUtil().product(123)

Personally I would rather do something like

result = n;
while (--n > 0) {
    result *= n;
}
return result;

Upvotes: 4

Renuka Deshmukh
Renuka Deshmukh

Reputation: 998

public int total = 1;

    public int product(int n) {
        for (int i = 1; i <= n; i++) {
            total = total * i;

        }
        return total;

    }

you havent initialized total. It defaults to 0. Then when you multiple anything with total, you get 0 as result

Upvotes: 1

Jernej K
Jernej K

Reputation: 1694

You are missing the initialization. Now I added the default value to 1. And you also have to change the condition. The for loop has to go on as long as the var i is smaller or equal to n.

public class MathUtil
{
  public int total = 1;

  public int product(int n)
  {
    for (int i = 1; i <= n; i ++)
    {
     total = total * i;
    }
   return total;

  }
 }

Upvotes: 2

Thomas Kis
Thomas Kis

Reputation: 21

you didn't initialized total, therefore it's 0. Whenever you multiply 0 with anything, you will get 0 as result.

Upvotes: 1

Related Questions