Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

System.in.read() 1

Status
Not open for further replies.

keizersoz

Programmer
Apr 22, 2004
67
0
0
BE

I use the method "System.in.read()" in order to read one char. But when I print out the output 2 other characters with asci '10' and asci '13' are read.

Which characters are those and how can I ensure to read only one character?

thanks
 
'10' is LF (line feed control char).
'13' is CR (carriage return control char).

See here :
This is standard practice - so you have to compensate for the LFCR characters in your code.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
or you might want to use the readLine() method.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Thanks guys,

One more question. In the following loop, see below:

while (true) {

System.out.println("Enter digit or -1 to exit");
input = (char) System.in.read();
System.out.print("input is:" + input+'\n');
...
}

I only once manage to enter input. The other times input equals space. How does this come and how can I change this?

Many thanks,

keizersoz

 
A user who tries to input '-1' will fail, because you read single characters, '-' and '1'.
The input is blocking, which means, the characters aren't passed when they are typed, but after hitting enter.

Code:
String line = null;
int value = -2;
do
{
	System.out.println ("Enter digit or -1 to exit");
	BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
	line = br.readLine ();
	value = Integer.parseInt (line);
	System.out.println ("input is:" + value);
	//  ...
} while (line != null && value != -1);
Using '\n' explicitly isn't a well idea too.
Use println instead, and the program will do the right thing, independent from the system where it is running (MacOs, Solaris, Linux, Windows, ...).

Using two indirections (BufferedReader, InputStreamReader) is annoying in the beginning, but the flexible consequence of OOP.

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top