Java扫描仪: stop reading after the first entry

标签 java input keyboard java.util.scanner

我正在寻找一种形式,使扫描仪在您第一次按下时停止读取(因此,如果我按K键,程序会自动考虑我按Intro 键,因此它会停止识别输入,保存 K 并继续执行程序)。

我一开始使用char key= sc.next().charAt(0);,但不知道如何在不按Intro的情况下使其停止 p>

提前致谢!

最佳答案

如果您想在单个特定字符之后停止接受,您应该逐个字符地读取用户的输入。尝试根据 Pattern 进行扫描单个字符或使用Console类。

Scanner scanner = new Scanner(System.in);
Pattern oneChar = new Pattern(".{1}");
// make sure DOTALL is true so you capture the Enter key
String input = scanner.next(oneChar);
StringBuilder allChars = new StringBuilder();

// while input is not the Enter key {
    if (input.equals("K")) {
        // break out of here
    } else {
        // add the char to allChars and wait for the next char
    }
    input = scanner.next(oneChar);
}
// the Enter key or "K" was pressed - process 'allChars'

关于Java扫描仪: stop reading after the first entry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36265402/

相关文章:

java - java中的线程生产者消费者

java - Coldfusion 获取给定 IP4 地址范围内的所有 IP 地址

c - float 输出不正确

java 从字符串中获取键码

android - 在android中创建 Activity 时如何获取键盘高度

shell - Emacs 中 char 运行模式 (ansi-term) 的键盘快捷键

jvm - sun.management.ThreadImpl#findDeadlockedThreads0 的 OpenJDK 实现在哪里

java - 摆脱 Collections.unmodifyingList() 产生的警告

c++ - 在 C++ 中读/写二进制文件

c - 仅读取文件中选定的数据