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

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

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

wz1wpwve

wz1wpwve1#

如果要在单个特定字符后停止接受,则应逐个字符读取用户的输入。尝试基于单个字符的模式或使用console类进行扫描。

  1. Scanner scanner = new Scanner(System.in);
  2. Pattern oneChar = new Pattern(".{1}");
  3. // make sure DOTALL is true so you capture the Enter key
  4. String input = scanner.next(oneChar);
  5. StringBuilder allChars = new StringBuilder();
  6. // while input is not the Enter key {
  7. if (input.equals("K")) {
  8. // break out of here
  9. } else {
  10. // add the char to allChars and wait for the next char
  11. }
  12. input = scanner.next(oneChar);
  13. }
  14. // the Enter key or "K" was pressed - process 'allChars'
olqngx59

olqngx592#

不幸的是,java不支持非阻塞控制台,因此,您无法逐个字符读取用户的输入(请阅读本文,以便回答更多细节)。
但是,您可以做的是,您可以要求用户输入整行并处理其中的每个字符,直到遇到intro,下面是一个示例:

  1. System.out.println("Enter the input");
  2. Scanner scanner = new Scanner(System.in);
  3. String input = scanner.nextLine();
  4. StringBuilder processedChars = new StringBuilder();
  5. for(int i=0 ; i<input.length() ; i++){
  6. char c = input.charAt(i);
  7. if(c == 'K' || c == 'k'){
  8. break;
  9. }else{
  10. processedChars.append(c);
  11. }
  12. }
  13. System.out.println(processedChars.toString());

相关问题