0
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?

6
Contributors
7
Replies
8
Views
6 Years
Discussion Span
Last Post by JeffGrigg
0

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 by Vaspar: n/a

0

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.

0

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.

0

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 by JeffGrigg: n/a

-1

I didn't realize that

for (;;)

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

Edited by hfx642: n/a

1

@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 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.