0

I've figured out im using the wrong loop for the task at hand but im still wondering why it repeats this exactly 3 times:

for(ch = (char) System.in.read(); ch != ('k' | 'K') ; ch = (char) System.in.read()) 
    {
        System.out.println("sorry, you're incorrect!\n Guess again: ");
    }

It prints this in the console if you don't hit k or K:

Sorry, you're incorrect!
Guess again:
Sorry, you're incorrect!
Guess again:
Sorry, you're incorrect!
Guess again:
[] <--represents where you would input next character

I'm just wondering why it's repeating three times, instead of once or four times, or inifinite times.

Edited by pyTony: fixed formating

3
Contributors
2
Replies
3
Views
11 Years
Discussion Span
Last Post by cheenu78
0

It's your structure. You need a while loop:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char c;
do
{
c = (char)br.readLine();
}
while (c != 'e');

Something like that.

0

hi
you are reading the line end characters as well, they are \r and \n in windows.
That is the reason why you are getting 3 lines of :

"Sorry, you're incorrect!"

than the expected one line.

As server crash said you can try with buffered reader which will remove line end characters, but readLine() will give you a String rather than char, you may not be able to type cast like:
c = (char)br.readLine();

I would suggest you to use the String and iterate to get the result.

I have modified your code a bit and avoided the line end characters.

import java.io.*;
class TestDani
{
	public static void main(String args[]) throws Exception
	{
		char ch = (char) System.in.read();
		while(ch != ('k' | 'K'))
		{
			if(ch=='\r'||ch=='\n')
			{
				ch = (char) System.in.read();
				continue;
			}
			
			System.out.println("sorry, you're incorrect!\n Guess again: ."+ch+".");
			ch = (char) System.in.read();
		}
	}
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.