java扫描器:在第一个输入之后停止读取

a7qyws3x  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(284)

我正在寻找一个表格,使扫描仪停止阅读时,你按第一次(所以,如果我按k键自动程序考虑,我按了介绍键,所以它停止识别输入,保存k,并继续与程序)。
im使用char key=sc.next().charat(0);在一开始,但不知道如何让它停止而不推动介绍
提前谢谢!

wz1wpwve

wz1wpwve1#

如果要在单个特定字符后停止接受,则应逐个字符读取用户的输入。尝试基于单个字符的模式或使用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'
olqngx59

olqngx592#

不幸的是,java不支持非阻塞控制台,因此,您无法逐个字符读取用户的输入(请阅读本文,以便回答更多细节)。
但是,您可以做的是,您可以要求用户输入整行并处理其中的每个字符,直到遇到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());

相关问题