Factorial

'void' type

Page 1 of 1

5 Replies - 801 Views - Last Post: 08 July 2010 - 02:27 AM Rate Topic: -----

#1 sh1n3  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 24
  • View blog
  • Posts: 164
  • Joined: 22-April 10

Factorial

Posted 07 July 2010 - 01:49 PM

Factorial.java:19: 'void' type not allowed here
return n*fact(n-1);
       ^
1 error
Press any key to continue . . .



That is the error message that I am getting. It's the first time I've ever seen anything like it!
The code is right below.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Factorial {
  public static void fact(int x) {
    int f=1;
    for (int i=1;i<x;i++){
      f*=i;
    }
    System.out.println(f);
  }
  public static int factr(int n) {
    if (n==1)
    {
      return n;
    }
    else
    {
      return n*fact(n-1);
    }
  }
  public static void main(String[] args)throws IOException {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter a Number : ");
    int input=Integer.parseInt(br.readLine());
    fact(input);
    int output=factr(input);
  }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Factorial

#2 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: Factorial

Posted 07 July 2010 - 01:54 PM

Your problem is that you are trying to return n * fact

fact is of type void...you need a number type

you declared the fact method as void so it doenst return anything
Was This Post Helpful? 1
  • +
  • -

#3 Locke  Icon User is offline

  • Sarcasm Extraordinaire!
  • member icon

Reputation: 521
  • View blog
  • Posts: 5,596
  • Joined: 20-March 08

Re: Factorial

Posted 07 July 2010 - 01:55 PM

On that line, you want to call factr, not fact.

return n*factr(n-1);


That should do it. :)
Was This Post Helpful? 1
  • +
  • -

#4 sh1n3  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 24
  • View blog
  • Posts: 164
  • Joined: 22-April 10

Re: Factorial

Posted 07 July 2010 - 02:05 PM

WOW solved, thanks....problems of a letter!! :)
Was This Post Helpful? 0
  • +
  • -

#5 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2872
  • View blog
  • Posts: 11,031
  • Joined: 15-July 08

Re: Factorial

Posted 07 July 2010 - 02:39 PM

yah fact() is your iterative solution. factr() is your recursive solution. Both should be independent and not reference the other as Locke pointed out.
Was This Post Helpful? 0
  • +
  • -

#6 jeremejazz  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 22
  • View blog
  • Posts: 48
  • Joined: 23-April 10

Re: Factorial

Posted 08 July 2010 - 02:27 AM

good!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1