Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What's Wrong With This Program  RSS feed

 
kiran mohan
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class IOStream1
{
public static void main(String[] args)
{
try
{
DataInputStream dis = new DataInputStream(System.in);
DataOutputStream dos = new DataOutputStream(System.out);

System.out.println("\nEnter Integer Value:");
int a=dis.readInt();

System.out.println("\nEnter Float Value:");
float f=dis.readFloat();

System.out.println("\nEnter Double Value:");
double d=dis.readDouble();

System.out.println("\nEnter Char Value:");
char c=dis.readChar();
System.out.println("\n Int Value Entered From KeyBoard Is:");
dos.writeInt(a);
System.out.println("\nFloat Value Read From KeyBoard Is:");
dos.writeFloat(f);
System.out.println("\nDouble Value Read From KeyBoard Is:" );
dos.writeDouble(d);
System.out.println("\nChar Value Read From KeyBoard Is:" );
dos.writeChar(c);
}
catch(Exception e)
{ System.out.println(e); }
}
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

DataInputStream reads, and DataOutputStream writes, the raw bytes that make up primitive values, wheras a human sitting at a keyboard types textual characters, which have to be translated into Java's internal representation for numbers.

An example: if you type the number "123", then you're actually typing the three characters whose Unicode values are decimal 49, 50, and 51. But DataInputStream would read that as 49x65536 + 50*256 + 51, or 324115! If you don't understand why, that's OK. Most introductory Java books will walk you through these ideas at some point.

Anyway, don't use these classes until the example above makes sense. The right way to read an "int" from System.in looks like this:
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!