0


In my code, I am stopping the thread after printing a character from a string in order to write the string letter by letter.
When the thread is stopped, meaning until the string is finished being printed, any key presses a user presses are not printed on the screen nor discarded. However, if there is a readLine() function after that, it picks up those stored key presses into the System.in input stream, and if the user presses enter, those key presses get instantly sent as an input. So my question is, is it possible to clear the System.in input stream and cancel those stray key presses?
My code:

val foo = "Hello World"
for (char in foo) {
     print(char)
     Thread.sleep(40)
}
val input = readLine()!! //ensure not-null
println(input)

Help is much appreciated.
Kotlin help is preferred, but Java answers will work just as fine.

The Shwarma
  • 180
  • 1
  • 11
  • what is `content`? From where do you get it? – Lino Jun 26 '20 at 10:57
  • @Lino sorry for not specifying, content is a String. – The Shwarma Jun 26 '20 at 10:59
  • I don't understand what a key press has to do with the code you pasted. – MissingSemiColon Jun 26 '20 at 11:44
  • @MissingSemiColon if you press any key while the Thread is paused, it'll be saved and pasted back when the thread is back on. – The Shwarma Jun 26 '20 at 11:49
  • My question is more where are you listening to the keyboard. I mean you can be reading from an input or listening to events. Generaly speaking thread are not stored, you are pausing the thread but the input is still there. Depending on how you are getting the keys the solution is different. – MissingSemiColon Jun 26 '20 at 12:01
  • 1
    This all depedns on the console you're using. My guess is that this is simply the console or a shell echoing what you type. For linux based consoles that's standard behavour. – al3c Jun 26 '20 at 12:09
  • @MissingSemiColon I'm simply using Kotlin's `readLine()` method. – The Shwarma Jun 26 '20 at 12:31

1 Answers1

1

You need to flush the buffer. Try System.out.flush() in Java. I'm not sure if this is the issue though. Some reference here

H. pap
  • 339
  • 1
  • 10