简体   繁体   中英

How do you set a pre-determined text as a user input with buffered reader?

Basically, how would I ask for a user input which would give out a default value right from the begenning for the user to edit. Eg. Asks the user to give a value while a default "1" is already typed in the text-field.

Calling the readLine() method on a BufferedReader doesn't create a "text field" analogous to a text input in a GUI application.

In theory what you want to do could be possible using a library such as RawConsoleInput . You would have to write a method which keeps track of the "input" in a stack of characters which is initialised to contain the default value. Then print the default value, and read keypresses one-by-one:

  • For most keypresses, push the key pressed to the stack, and print it so it appears on the console.
  • When the backspace key is pressed, pop from the stack and print the \b escape sequence to simulate a backspace in the console.
  • On the enter key, stop reading keypresses, print \n and return the stack contents as a string.

This solution will not be cross-platform compatible, because there is no cross-platform way to do non-line-buffered console input, and some consoles (eg the one built into Eclipse) don't handle \b properly.

The much simpler and almost certainly better way to have a default option is just to tell the user what the default is, and let them press 'enter' without typing anything to get the default.

If you're using a console, that's not going to work. It only reads what actually comes in through the input stream. You can display a "1", but that is output, not input. Also, don't expect them to be able to delete the "1".

What you can do is assume a default value if they don't enter anything. You can also collect their input and just stick a 1 at the beginning of the string after you read it.

Also, why are you trying to do this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM