Java Scanner:第一次输入后停止读取

时间:2016-03-28 15:25:37

标签: java input keyboard java.util.scanner

我正在寻找一张表格让扫描仪在第一次按下时停止阅读(所以,如果我自动按下 K 键,我会按下该程序简介键,因此停止识别输入,保存 K 并继续使用该程序。)

我在开头使用 char key = sc.next()。charAt(0); ,但不知道如何在不推送 Intro 的情况下停止

提前致谢!

2 个答案:

答案 0 :(得分:1)

如果要在单个特定字符后停止接受,则应逐个字符地读取用户的输入字符。尝试根据一个单个字符的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'

答案 1 :(得分:0)

不幸的是,Java不支持非阻塞控制台,因此,您无法逐个读取用户的输入(阅读this SO答案以获取更多详细信息)。

但是,你可以做的是,你可以要求用户输入整行并处理它的每个字符,直到遇到 Intro ,下面是一个例子:

System.out.println("Enter the input");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
StringBuilder processedChars = new StringBuilder();
for(int i=0 ; i<input.length() ; i++){
    char c = input.charAt(i);
    if(c == 'K' || c == 'k'){
        break;
    }else{
        processedChars.append(c);
    }
}
System.out.println(processedChars.toString());
相关问题