• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help me out

 
Yudi Strange
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am really new to java programming. I thought i would begin with a factorial generating program with the input taken from the keyboard.
The program is compiling well and is running too but the output is always 0.
There seems to be something major which i am missing out. kindly help me.
The code is as follows:




import java.io.*;
class fact
{
public static void main(String []a)
{
int i=0,temp=1,j=1;
BufferedInputStream q= new BufferedInputStream(System.in);
try
{
System.out.println("Enter the no. whose factorial is to be found.....");
i=q.read();
q.close();
}
catch (Exception e)
{
System.out.println("Exception ecountered");
}
for(j=1;j<=i;j++)
temp=temp*j;
System.out.println("\n\n\nThe factorial of the no. is \t"+temp);
}
}
 
Lalit Bhatt
Ranch Hand
Posts: 69
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should use StreamReader like this



If you are in Java 5 use Scanner.

Also try to use ide and use the debugging features. You can see a tutorial on eclipse id here
 
W Pearce
Ranch Hand
Posts: 32
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Usually I wouldn't write a full code listing, but I remember trying to learn recursion and how much of a pain it was so try this out:



Now when you enter a 5, for example, it will return 120. This will also return 1 if 0 is entered, as suggested by Mr Ritchie below.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lalit Bhatt wrote:Also try to use ide and use the debugging features. You can see a tutorial on eclipse id here
Disagree. If you are a beginner, it is more likely that the many features of an IDE will confuse you. Learn Java from the command line, then use an IDE (I think Eclipse is a very good tool) once you are familiar with Java.

And welcome to JavaRanch

That is a possible way to calculate a factorial, but I challenge you to do it the way the mathematicians would, where you return 1 when the input is 0. Also find out what the largest argument that method will take before giving an error because of arithmetic overflow.
 
Yudi Strange
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic