Assuming I have something like this:
x= (char) System.in.read();
if(x == 'a') {
// Do something;
}
How much different is it from something like:
public void handle(KeyEvent event) {
switch (event.getCode()) {
case A: // Do something;
case ENTER: // Do something else;
}
}
I mean when should I use the first and when the second? What are the pros and cons?
The two approaches are getting input from the user in two different ways.
The first is reading characters from the JVM's "standard input" stream. If you ran your application without redirecting standard input, this stream is likely to be coming from the "console window" where you launched the JVM. The keystrokes on the console window are processed by the console / OS line editor until the user types ENTER. When that happens a line of characters is delivered to the input stream ready to be read by the JVM / Java application.
The second is processing keyboard events directly. However, this only works in a GUI application. It only sees the keyboard events directed at the application's window(s).
Use the first in a console-based where you don't need to see characters at the instance the user presses a key.
Use the second when you have a GUI based application and you want to get input from the user interactively.
That is self-evident from the above. However, there are a couple additional "cons".
With the System.in approach:
System.instream could be coming from a file. If you need to be sure (or as sure as possible) that you are talking to a real user, useSystem.console()... and check that you don't getnull.With the
EventHandlerapproach: