Ender:
Your program is working correctly. Since this is a console application, every time you hit enter it prints the character entered plus the carriage return and line feed. For example, if you entered 'S' and hit return, it would look like this:
S\r\n
So, your suspicions were correct. It was the '\r' and '\n' that caused your problem.
When you were hitting a character your program logged three passes. One for the character 'S', one for the carriage return '\r', and, finally, one for the line feed '\n'.
I took your code and altered it a bit.
You simply make sure you are processing only the chars you are interested in and ignore the rest. I saw that you did this in some of your other code. See the code below:
// Begin irritating program # 1
import java.io.*;
class AnnoyingForProg
{
public static void main(
String args[]) throws java.io.IOException
{
int i = 0;
char c;
System.out.println("Press S to stop.");
while( ( c = ( char )System.in.read() ) != 'S' )
{
if( (c >= 'a' && c <= 'z' ) | | ( c >= 'A' && c <= 'Z' ) )
{
i++;
System.out.println("Pass # " + i);
}
}
}
}// End first irritating prog.
Looks like you are already on the right track.
Happy programming!!
-Bryan
OK, I would be expecting output something along these lines...
But instead I get this!!!
If I press ENTER it loops twice, not once, before prompting me again. If I enter a wrong character, it loops thrice! Why is this? How can I prevent it?
Here is another example of odd output in a somewhat similar program.
OK, this one does a very similar thing. Three loops when I press a character, two loops if I press enter.
Now something that confuses me a little more, but also makes me wonder if it is line buffered input is this program, which works just fine:
OK, this one gives me PERFECTLY normal output. Only one prompt and one pass per entry. Nothing weird here. In this one I added an exclusion for line feeds and carriage returns. I suspect these are the culprits in AnnoyingForProg and AnnoyingDWhileProg, but I am not 100% certain. Could some Java guru give me a hand here and explain what's going on?
Thanks a million, and again, sorry for the excessively long post.
-Ender
[This message has been edited by Ender Everett (edited June 01, 2001).][/b]
</BLOCKQUOTE>
[This message has been edited by Bryan Fagan (edited June 03, 2001).]
[This message has been edited by Bryan Fagan (edited June 03, 2001).]