【发布时间】:2021-03-31 11:02:47
【问题描述】:
代码:
import java.util.Scanner;
public class Try{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String : ");
String s = sc.nextLine();
System.out.println("The Entered String is : " + s);
System.out.println("The Length of Entered String is : " + s.length());
sc.close();
}
}
输出:
┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $java Try
Enter a String :
hello
The Entered String is : hello
The Length of Entered String is : 5
┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $java Try
Enter a String :
hello^[[C
The Entered String is : hello
The Length of Entered String is : 8
当我按箭头键时 ^[[C 出现而不是光标移动(其他箭头键、转义键、home、end 也会发生类似的事情)!
这里发生的事情是字符串第二次包含字符:
['h', 'e', 'l', 'l', 'o', '\x1b', '[', 'C']
因此,'\x1b', '[', 'C' 是从键盘发送到外壳的字符序列,用于表示右箭头键(向前光标)。
我想要的是这些字符不会显示在外壳中,但光标会移动(根据按下的键向前、向后、到家、结束等)。
输入后处理意义不大,主要目的是让光标移动!
如何在 Java 中实现这一点?
[编辑]
唯一的目标是在使用程序时为用户提供与终端一样的体验。
【问题讨论】:
-
我不确定这是否可以从 Java 本身实现,因为击键首先由您的命令行处理并映射到这些控制字符。然后 Java 将接收来自 shell 的输入,而不是相反。
-
@Thomas 据我所知它可能适用于 c 和 c++ 但 java 我不确定
-
@Thomas 我会调查它,如果我能找到解决方案,我会在这里更新它
-
@Thomas 但您提供的链接是针对 C# 的,但 Java 控制台类非常有限,提供的内容不多!
-
哦,是的,你是对的。我的错,没有检查这个。我会删除评论。