0

For example, I want to use a keyboard to input a name, but I made a mistake and would like to correct it. So I use the backspace key and try to delete the character I entered. It seems it took the backspace as an input as well. How can I ignore the backspace and correct my input?

gnohz
  • 3
  • 1

2 Answers2

1

You can use a ScannerObject if you are getting the input from keyboard

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    while(sc.hasNext()){
        System.out.println(sc.next());
    }

    sc.close();
}
javaBean007
  • 555
  • 6
  • 11
  • It is so weird that even I type "j", it gives j^?j, and if I enter the backspace key, it gives me "^?". But other inputs are fine. – gnohz Nov 22 '17 at 05:07
  • @Jie What happens if you type, say, "abc", CONTROL-H, "def"? Does it backspace then? I'm wondering if there's a disconnect between the OS and the keyboard. Historically, some OS's have used DEL (ASCII 127) to erase the last character, which shows up as `^?`, and some have used BS (ASCII 8), which you get with control-H. These days, modern OS's understand "key presses" instead of ASCII codes. But if you're using one OS to log in remotely to some other machine running a different OS, it seems possible that the problem is a mismatch in what character it expects to be the "backspace". – ajb Nov 22 '17 at 05:27
  • @ajb You are totally right. I edit my file in spacemacs, and also use the shell inside it. Then I use ssh to remotely run the code. Both give me the same errors. After reading your comment, I changed to use the terminal directly, it works, even with BufferedReader class. Thanks very much! – gnohz Nov 22 '17 at 05:40
0

Use console instead

  Console c = System.console();
    if (c == null) {
        System.err.println("No console.");
        System.exit(1);
    }

    String login = c.readLine("Enter your login: ");
Yu Jiaao
  • 4,444
  • 5
  • 44
  • 57