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?
Asked
Active
Viewed 813 times
0
-
is it took the backspace as an input? is that in the java console? – Kenry Sanchez Nov 22 '17 at 04:30
-
I use System.in – gnohz Nov 22 '17 at 04:31
-
Are you using Scanner or BufferReader? – DevilsHnd - 退職した Nov 22 '17 at 04:32
-
use Scanner object – arjunsv3691 Nov 22 '17 at 04:32
-
I use BufferedReader. So I should use Scanner instead? – gnohz Nov 22 '17 at 04:34
-
You won't have that issue by using the Scanner Object – DevilsHnd - 退職した Nov 22 '17 at 04:37
-
Please post your code. I don't think you should get that issue with `BufferedReader` either, or with any *normal* input method. You pretty much have to be looking for individual key presses in order for a backspace not to work as a backspace. – ajb Nov 22 '17 at 05:19
2 Answers
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