简体   繁体   中英

Typed text displays in console when not asking for input, how can I stop this?

I'm trying to make a simple text-based game using Java in Eclipse, and everything was working just fine until it randomly started to allow you to type at any point in the program instead of just when requesting input with a Scanner . I found this really weird and did what I could to fix it but nothing worked, so now I'm back at square one. When I run my program, I can type anywhere in the console and it actually shows up and I don't want this to happen. This is my first few lines of code and there are obviously no Scanners in here so I don't understand what could be the problem.

This is happening in all of my projects and I really want to get back to coding with it working.

import java.util.Scanner;

public class Game {
public static void main(String[] args) throws InterruptedException { 

    String com = "Computer: ";

    System.out.print(com +"H");
        Thread.sleep(75);
    System.out.print("i");
        Thread.sleep(75);
    System.out.println(".");

    Thread.sleep(2000);

This is normal behavior for most consoles; it's not coming from Java or your Java code. When you type into the console, it echoes the characters you type back to you.

There do exist ways to turn off echoing. Console.readPassword() will turn it off until you hit Enter . Unfortunately, Console doesn't expose the ability to turn echoing on and off directly, only while asking for a line of input.

The JLine library can turn it on and off with Terminal.echo() :

Terminal terminal = TerminalBuilder.terminal();
terminal.echo(false);

Whether this works right might depend on the way in which the program is run; I haven't tried it from Eclipse.

When I tried this, what I typed while echoing was off appeared the next time I turned echo on. Once again, normal console behavior. If you're typing into the console, it's always listening to you. If you don't want that, I found a hack around it, that worked once or twice at least:

// Skip over anything that's been typed in already.
// Re-implementing skip() with read(), because skip() can throw an "Illegal seek"
// error that read() won't.
System.in.read(new byte[System.in.available()]);
terminal.echo(true);

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