How to accept input from keyboard
If you need to write interactive text-based application in Java, you will need a way to accept input from the keyboard; sure you can get it from the command line, but at some point, you will need to prompt the user for an input and store that input somewhere in your code for later processing.
There are lots of ways to do that, this is one of them.
The captured input from the keyboard is already trimmed, there is no need to call temp.trim(); The last System.out.println(“Length …”) is just for show, you can omit that line–it’s just there for show-and-tell.
The second example is a bit more modularized–in most situations, what you will need is a function in your code that you can call every time you need to prompt the user for input; it would be handy too if this function accepts a String object as parameter which will be displayed as a prompt to the user, and finally, the function should return what the user has typed–here is the code for that.
This will tie you up if you just need some simple mechanism to display a prompt and get input from the user using text-based interfaces. If you need something more advanced like windowing, positioning the prompts on very specific screen coordinates and coloring the fonts — that will be a bit more involved to code; you’re probably better off using some of CURSES related Java libraries like JCurzez, CHARVA and Java Curses — Note though that I haven’t tried anyone of these 3, but these are the ones I found by quickly Googling ‘java curses’–that seemed like a good search phrase at the time of writing.
If you want to show appreciation for my efforts dear reader, you could buy me a tall hazel nut Americano ($2) via PayPal. Thanks
Leave a comment