views:

996

answers:

3

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
+4  A: 

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.in is an input stream, and System.out and System.err are 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 Console object (from System.console()) instead. Specifically, the readPassword() method doesn't echo whatever the user types back to the console. However, there are three problems with this approach. First of all, the Console class 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.out and System.err are both instances of PrintStream, but PrintStream is pretty much just a flexible version of OutputStream—a PrintStream is still like a normal output stream in that outputting is a one-way operation.

htw
Even in C, there is no standard way to clear the screen.
Matthew Flaschen
A: 

You will struggle to do this with the standard library.

If you don't want to do it yourself, you may be able to do this with a 3rd party library like JLine.

McDowell
A: 

huh - I always assumed that if you sent backspace characters ('\b') to sysout that it would clear - but I never actually tried it (don't do much console programming these days).

Haven't tried that, but the bottom of this thread seems to indicate that it should work.

Note that this might not work in an IDE console, but may work in a regular OS console...

I'll leave actually proving for certain that it works as an exercise to the OP :-)

Kevin Day