I’m using the Scanner class to take some input from the user through the console. Whenever the user inputs something in the screen and presses enter the input stays on screen for example:
This is the prompt
// User writes command and presses enter
- command
- output of command goes here
//Use writes command3
- command
- output of command goes here
- command3
- output of command3 goes here
Is there anyway I can make the command entered not stay in the console after pressing enter?
For example:
//User writes command
- output of command goes here
Short answer: no, not from directly within Java. Java has very limited control over the console: you can only read and write to it. Whatever is displayed on the console cannot be erased programmatically.
Long answer: in Java, all console operations are handled through input and output streams—
System.inis an input stream, andSystem.outandSystem.errare output streams. As you can see for yourself, there is no way to modify an output stream in Java—essentially, all an output stream really does is output bytes to some destination (which is one reason why it’s called a “stream”—it’s one-way).*The only workaround I can see is to use a
Consoleobject (fromSystem.console()) instead. Specifically, thereadPassword()method doesn’t echo whatever the user types back to the console. However, there are three problems with this approach. First of all, theConsoleclass is only available in Java 1.6. Second, I wouldn’t recommend using this for input other than passwords, as it would make entering commands more troublesome than it’s supposed to be. And third, it still wouldn’t erase the prompt from the screen, which would defeat the purpose of what you’re trying to achieve, I’d think.* – Technically speaking,
System.outandSystem.errare both instances ofPrintStream, butPrintStreamis pretty much just a flexible version ofOutputStream—aPrintStreamis still like a normal output stream in that outputting is a one-way operation.