• Post Reply Bookmark Topic Watch Topic
  • New Topic

java.io.console question  RSS feed

 
Scott A Burch
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a console application, the purpose of which is to write a byte to a network socket using a TimerTask. Compiling gives me an error on line 23 - which I knew would happen - that the variable deviceSocket cannot be found. I created it in the main section of the program because that's where the user answers questions about start and stop times, and IP address and port info. My problem is that I'm stuck for alternatives - how can I restructure this so that the variable can be found? It has to be in the StartTask TimerTask because the byte needs to written only when StartTask executes. Is it possible to ask for console input outside the main section of the program? When I tried that, I wound up with lots more errors and got really lost. Thanks!




 
Knute Snortum
Sheriff
Posts: 4281
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to look at java-avm.
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Beware of java.io.Console. If you open the app from an executable .jar with the javaw or javaws tool (I think one of those two actually exists!), rather than with java at the command line/terminal, then no Console object will exists and any attempt to use it will cause a null Exception.
Why are you using DateFormat? Like such classes as Date and Calendar, look on that as legacy code and, instead, use one of the Java8 time classes (try the formatting section).
Why have you got an empty catch block? That is dangerous because Exceptions can occur and you don't find out about them.
Why have you marked so many things static?

Why are you trying to create fields in the main method? That is not what the main method is intended for. It is intended for starting your app. Full stop. Nothing else. Unless you need to pass information about the location of the device socket via the command‑line arguments of similar, why are you not making it a field of that class and initialising it via its constructor? Of course you can get console input anywhere. You can write this sort of thing anywhere
Console console = System.console();
… but I believe (not certain) you will get the same instance every time.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!