Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

reading integers using System.in

 
swapnil dey
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
so far ive used following code for reading integers from std i/p
DataInputStream ds= new DataInputStream(System.in);
int i= Integer.parseInt(ds.readLine());
can i not use 'readInt()' of DataInputStream to read integers from std i/p. if yes how, if no why
int i= ds.readInt() gives a weird value... any explainations
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi dey!
when we accept input from keyboard it will be always string only.
we cannot accept integer values directly.when u read the input (even if the input is integers), that will be treated as string.so when u said "ds.readInt()" , it is returning the unicode value of the integers u are accepting from keyboard.
i hope i could answer your question.
bye
 
Serge Plourde
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Swapnil
bkkumar is right.
In the API, for DataInputStream, you can read:
readLine() Deprecated. This method does not properly convert
bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
DataInputStream d = new DataInputStream(in);
with:
BufferedReader d = new BufferedReader(new InputStreamReader(in));
In addition to this, the DataInputStream is not compatible with the BufferedReader.
So, in order to read the whole "line" of input, use the BufferedReader, as suggested.
Here is "one" of the many way of writing the code:
 
Serge Plourde
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I forgot to tell you, DataInputStream is really meant to handle data generated by DataOutPutStream. That's why you can't directly use readInt().
 
swapnil dey
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys
thanx for helping, point taken
now i have few more related problems
say i create a form, n i wanna store the data in a binary file using DataOutputStream. when i try reading info from the file (using DataInputStream) there are no problems if the data is numeric,
but while reading text fields i get a warning coz readLine is deprecated ( as pointed out by bkkumar ), readBytes would require me to provide the number of bytes to be read,
i can't use Reader classes out there coz the result would be a text file which i don't want
is there any way out...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic