How to make a Gpars Actor to read from console

57 Views Asked by At

I have a simple GPars actor:

class ConsoleActor extends DefaultActor {

    protected void act() {
        loop {
            react { Msg msg ->
                switch (msg.type) {
                    case MsgType.Read:
                        sender.send(System.console().readLine())
                        break
                }
            }
        }
    }
}

But when I try to send a message to force the actor to read from Console, i get a NPE:

An exception occurred in the Actor thread Actor Thread 3 java.lang.NullPointerException: Cannot invoke method readLine() on null object

Why this happens and how to read from console in a GPars Actor?

1

There are 1 best solutions below

0
On

I found the answer here: StackOverflow - System Console returns null

class ConsoleActor extends DefaultActor {

    protected void act() {
        loop {
            react { Msg msg ->
                switch (msg.type) {
                    case MsgType.Read:
                        Scanner input = new Scanner(System.in);
                        String str = input.nextLine();
                        sender.send(str)
                        break
                }
            }
        }
    }
}

It works for me.