Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

java - System.in.read() behaviour i can't explain

class E92StringDemo {

    public static void main(String args[]) throws java.io.IOException {

        String strObj1 = "First String";

        for (int i = 0; i < strObj1.length(); i++) {

            System.out.print(strObj1.charAt(i));
            System.in.read(); //just to pause the execution till i press enter key

        }
    }
}

I want the output to come like:

F
i
r
s
t...

but the output is coming like:

F
ir
st
S
tr
in
g

I am not sure how come 2 characters are getting displayed in one line with every press of an enter key( )?

I am running windows 8 and using a command prompt to run the file using javac.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem

System.in.read() only holds execution of your application if there is no data to read in standard input stream (represented by System.in).

But in console when you press ENTER, two things happen:

So as you see if you want to pause your loop in each next iteration, you will need to empty data from input stream before leaving current iteration. But System.in.read() reads only one character at a time, in your case leaving for next iteration (so no pause there).

So before pause will be again available you need to read twice in one iteration.

Solution

If you want to get rid of this problem in OS independent way use BufferedReader#readLine() or Scanner#nextLine like:

String strObj1 = "First String";
try(Scanner sc = new Scanner(System.in)){//will automatically close resource
    for (int i = 0; i < strObj1.length(); i++) {
        System.out.print(strObj1.charAt(i));
        sc.nextLine();
    }
}

These methods also solve problem of potential extra characters placed before pressing enter, since each of them will also be placed in standard input stream, which would require additional .read() calls.


* along with rest of potential characters which ware provided before pressing enter


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...