简体   繁体   English

Java扫描器或缓冲读取器

[英]Java Scanner or Buffered Reader

I have a requirement where I will have to read inputs from console not from file 我有一个要求,我必须从控制台而不是从文件中读取输入

The input format is as below.I understand I can use any character to exit .But i cannot give any other input than this.Can i write some thing like wait for a specific amount of time and if there is no input break the loop or else what else can be done to read input whose length we never know before hand. 输入格式如下。我理解我可以使用任何字符退出。但是我不能给出任何其他输入。我可以写一些东西,例如等待特定的时间,如果没有输入则中断循环或否则,可以做其他什么来读取我们之前从未知道过的长度的输入。

Hello,Agnes 你好,艾格尼丝
Minion,Bedo 奴才,Bedo
Vector,Shrink Ray 矢量,收缩射线

This following logic will make the readline wait forever for the input and wouldn't help because every enter I press will again be another input character and it never ends. 以下逻辑将使readline永远等待输入,并且无济于事,因为我按的每个输入将再次成为另一个输入字符,并且永远不会结束。

I neither wanna give any exit character to determine end of input like "exit". 我既不想给出任何退出字符来确定输入的结束,例如“退出”。 How to handle this?? 如何处理?

ArrayList<String> emp=new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
h=br.readLine();
while((h=br.readLine()) != null)
{           
   emp.add(h);         
}

You could add a thread that requests the users input, and then a Timer that's started over on each new input. 您可以添加一个请求用户输入的线程,然后添加一个在每个新输入上重新启动的Timer。 When the timer expires, it shuts the user input thread down. 计时器到期时,它将关闭用户输入线程。

    Scanner reader = new Scanner(System.in);
    System.out.println("Enter something: ");
    String s=reader.nextLine();
    System.out.println("You enetered: " + s);

Which results in: 结果是:

Enter something: 
Mike,Elofson
You enetered: Mike,Elofson

Generally speaking, and from my experience, scanners are easier and more commonly used for input. 一般来说,根据我的经验,扫描仪更容易使用,更常用于输入。

How about a "" input(namely press Enter directly), or two/three consecutive "" inputs. “”输入(即直接按Enter键)或两个/三个连续的“”输入怎么样?

I don't think waiting for some time is a good idea. 我认为等待一段时间不是一个好主意。 Anyway, you need some input to indicate the end. 无论如何,您需要一些输入来指示结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM