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.

Recommended Answers

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.

Jump to Post

All 2 Replies

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.

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();
		}
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.