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?

Recommended Answers

All 7 Replies

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;
                        }
		}
	}
}

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.

Member Avatar for hfx642

I'm surprised that it compiled at all.
There is nothing in your "for" statement.

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.

Member Avatar for hfx642

I didn't realize that

for (;;)

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

@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

Be a part of the DaniWeb community

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