• Post Reply Bookmark Topic Watch Topic
  • New Topic

readInt()

 
Rashi Gulati
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I am facing a problem i am trying to read a integer from the keyboard by creating DataInputStream, and using readInt() function but i came to know that readInt() function actually calculates the binary values that's why it is not giving the appropriate result, so my question is then where we use readInt() function when it cannot read an integer. Please help
int input()
{
try
{
dataInput= new DataInputStream(System.in);
System.out.print("Enter the number :");
number=dataInput.readInt();
System.out.println("Number is :"+number);
}
catch(IOException e)
{
System.out.println("Exception"+e);
}
return number;
}

Regards
Rashi
 
Joe Ess
Bartender
Posts: 9361
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look at the documentation for DataInputStream it says:

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.

The System.in stream is not written by a Java application. It is written by the Unix shell or the Windows command program so we can't use DataInputStream to intrepret the contents of that stream. The documentation states that DataInputStream expects a 4-byte integer. The System.in stream provides a stream of bytes, each byte representing an individual key press, so it is no surprize you are getting weird results.
Your best bet is to read the input in as a String using BufferedReader and use the methods of java.lang.Integer to parse an int out of the input.
[ July 26, 2004: Message edited by: Joe Ess ]
 
Rashi Gulati
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Joe now i got it.

Regards
Rashi
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!