public class TestMySource {
	public static void main(String args[]) 
			throws java.io.IOException{
		char ch;
		for (;;) {
			
			System.out.print("Please insert a char: ");
			ch = (char) System.in.read();
			if (ch == '.') {
				break;
			}
		}
	}
}

output: Please insert a char: Please insert a char: Please insert a char: a
Please insert a char: Please insert a char: Please insert a char: s
I can't explain why print "Please insert a char:" 3 times and then i can insert a char?

use Scanner Reader.... as String and Get char at index 0

import java.util.Scanner;

public class TestMySource {
	public static void main(String args[]) 
			throws java.io.IOException{
            Scanner sc = new Scanner(System.in);
                String s;
		char ch;
                for(;;)
                {	
			System.out.print("Please insert a char: ");
			s = sc.next();
                        ch= s.charAt(0);
                        if(ch=='.'){
                            break;
                        }
		}
	}
}

Edited 5 Years Ago by Vaspar: n/a

In your original code insert a print statement immediately after line 88 (in.read) to print the value of ch. Then you will be able to see exactly what's happening.

you don't actually need anything in your for statement. It will result in an infinite loop though, unless you use a break statement, like the OP used.

Your for (;;) statement is just fine. It works just like while (true) .

To answer your original question: You get so many prompts because 'System.in' does not and cannot give you character-by-character input. It can only read a line at a time. It's getting input a line at a time, but you are printing a prompt for each and every character in the line.

Edited 5 Years Ago by JeffGrigg: n/a

I didn't realize that

for (;;)

would work.
Still... I think that it's poor programming practice.

Edited 5 Years Ago by hfx642: n/a

@hfx642: As defined in the language (to be just like C/C++) for (;;) works exactly like while (true) . A fairly large number of people in the field seem to think that this is good, and they do use it. I've always thought of it as kind of pointless, odd, and misleading. I think that for (;true;) would make more sense. And because it's essentially while (true) , I always use that instead. And I typically refactor one into the other.

to each his own

This article has been dead for over six months. Start a new discussion instead.