1

In this question, it was suggested to use Console.in.read.toChar. It works fine in REPL, but fails to work when I put it into a script (requires user to press Enter):

#!/usr/bin/scala
!#

while (true) {
  val c = Console.in.read.toChar
  println("Got " + c)
}

So when I type a char and press Enter, I get

Got a
Got

I'm using Scala 2.9.0.1, on Ubuntu 11.04, in gnome-terminal.

What am I doing wrong?

Community
  • 1
  • 1
Rogach
  • 26,050
  • 21
  • 93
  • 172
  • Look at the docs for Console.in, and see how to change the buffering. – dave4420 Dec 20 '11 at 08:55
  • @dave4420 - and where should I look about changing buffering? BufferedReader does not seem to have a method for this. – Rogach Dec 20 '11 at 09:14
  • No idea :-( I'm a beginner at Scala myself. But this problem turns up time and again in many different languages, and it's usually something to do with buffering. – dave4420 Dec 20 '11 at 09:58

2 Answers2

3

Take a look at the answers given to a similar question here.

The issue is that the console in Java and therefore Scala is in buffered mode and needs to be in raw mode to return individual characters instead of lines.

Switching to raw mode is platform specific issue which is, I guess, why it's not directly supported by Java. I assume that the REPL has set raw mode somehow.

Community
  • 1
  • 1
Don Mackenzie
  • 7,953
  • 7
  • 31
  • 32
-5

Reading input from user, one char at a time (in script or compiled app)? Reply

<input type='text' id='userinfo' />
<br />
<br />
<p id="output" style="color:red; font-size:3em" >  </p>

<script type="text/javascript">
    document.getElementById("userinfo").onkeyup = function (){
        document.getElementById("output").innerHTML = this.value;
    }
</script>
jim
  • 1