• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

reading data from keyboard

 
krish reddy
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is a program which im trying for sum of a harmonic series, the value of n should be given by the keyboard.im confused
import java.io.DataInputStream;
class harmonic
{
public static void main(String args[])
{
DataInputStream in=new DataInputStream(System.in);
int n=0;
int i;
float sum=1;
try
{
System.out.println("Enter an interger: ");
n=Integer.parseInt(in.readLine());
}
catch(Exception e){}
for(i=1;i<=n;i++)
{
sum=sum+(1/i);
}
System.out.println("sum of harmonic series ="+sum);
}
}
the answer i always get is 2
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch! The result of dividing an int by an int is an int; after the first one, your division always comes out to zero, as fractional parts are truncated.

Instead do something like



By making one of the operands a float, the result becomes a float.
 
krish reddy
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank u very much, the program is working now, i have been preparing for scjp and this has been a good start.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic