aspose file tools*
The moose likes Beginning Java and the fly likes Help me out Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help me out" Watch "Help me out" New topic
Author

Help me out

Yudi Strange
Greenhorn

Joined: Jun 04, 2009
Posts: 7
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

Joined: Dec 27, 2007
Posts: 69

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


Java-JavaEE Hibernate Spring Software Development Business Process Analysis
W Pearce
Ranch Hand

Joined: Jan 06, 2009
Posts: 32
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.


SCJP 6, SCWCD 5
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38865
    
  23
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

Joined: Jun 04, 2009
Posts: 7
Thanks to all
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help me out