Unexpected result in simple java program

I'm new to java and my problem is that the output shows 2 numbers after a key is pressed and I don't understand why.

This is the code:

class ForTest {    
    public static void main(String args[]) throws java.io.IOException {
        int i;
        System.out.println("Press S to stop.");
        for(i = 0; (char) System.in.read() != 'S'; i++)
            System.out.println("Pass #" + i);
    }
}

      

+1


source to share


4 answers


Although I cannot reproduce the problem: ( See here ) my suggestion is to print the symbol (as integer). This will help you debug:



for(i = 0; (char)( int c = System.in.read() ) != 'S'; i++)
   System.out.println("Pass #" + i + ": " + c);

      

+1


source


I have a feeling that your problem is related to buffered I / O. I am assuming that between your "keystrokes" you get into the game? On most systems, I / O is not flushed until the input receives a new line. The problem is that the buffer then has a newline in it, which is calculated according to the number of characters in your loop.

Edit:



If this is indeed the case, it seems you want your "passes" to be the number of lines before you hit the line consisting of only "S." If so, try using something like this:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class ForTest {
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int i;
        System.out.println("Press S to stop.");
        for(i = 0; !br.readLine().equals("S"); i++)
            System.out.println("Pass #" + i);
    }
}

      

+1


source


I tested your program and I think I see the problem, if you look closely, you can see that when you do two keystrokes, you have 3 outputs, when you do three keystrokes, you have 4 outputs, etc. etc. The problem is that it System.in.read()

counts the newline as a character, so you will always have another output.

+1


source


See the description of the read method in the input stream. Inside, he makes 2 calls. If the first call results in an IOException, it will make another call again, which returns an IOException .. then it will be treated as the end of file.

http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

+1


source







All Articles