Link to home
Start Free TrialLog in
Avatar of samliam
samliam

asked on

reading standard input

Why doesn't this work:

System.out.println(" Select mode: ");  
DataInputStream dis = new DataInputStream(System.in);
int selection=dis.readInt();
if(selection==2){.....
}else{....}


Avatar of k.jones
k.jones

It does not work because DataInputStream is for reading primitive Java types.  (It also deals with unicode characters rather than bytes.)  You are not reading primitive Java types such as 'int' when you are reading console input.  Use a plain old InputStream to read the console.  You will have to read the String representing the integer and parse/convert it to an int.

Cheers,
Ken Jones
one more thing apart from what k.jones has said is that while you are creating any input/output stream dont forget to handle the exception, its a must
by the way please specify the error u r getting
ASKER CERTIFIED SOLUTION
Avatar of Jim Cakalic
Jim Cakalic
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of samliam

ASKER

How do you come up with "CTRL-@ CTRL-@ CTRL-@ CTRL-B"?
There is a keyboard control sequence for every ASCII control character. For example, the familiar newline character (decimal 10) is CTRL-J. J happens to be the 10th letter of the English alphabet. The familiar carriage return (decimal 13) is CTRL-M. Can you guess the cardinal value of the letter M?

To generate a NUL byte, decimal 0, is CTRL-@. To generate a byte with a binary value of 2 would be CTRL-B. Since an integer is a 32-bit (4 byte) quantity, simulating an integer on the input stream requires three 0 bytes and a binary 2 byte. So: CTRL-@ CTRL-@ CTRL-@ CTRL-B.

:-)
Jim
the first answer from jim is tricky one,
 that does solve the problem for the programmer but not for the potential user,

as one cannot ask the user to input a number '2' by some strange(not to me) sequence of keys. why would he do that.
 are you going to suggest in the user manual that to enter one number press combination of ctrl'ed 4 keys.

 anyways thanx jim for sharing the NICE CTRL information
happy coding
My comment was originally intended to be humorous. Why, indeed, would this be the "standard" UI mechanism? I was definitely smirking as I wrote it. But not knowing samliam's needs, I tried to provide both a correction to usage based on the original code -- that could be what was needed -- as well as a code fragment that demonstrated the way input is usually collected from System.in when a human is anticipated to be the data provider.