Java:如何在控制台程序中不使用Ctrl + Z的情况下使用scanner.hasNextLine [英] Java : How to use scanner.hasNextLine without Ctrl+Z in a console program
问题描述
说我有以下代码
扫描仪扫描仪= new Scanner(System.in);
而(scanner.hasNextLine()){
line = Scanner.nextLine();
//做某事
}
我在控制台中输入的内容是
Wayne Rooney
Luis Nani
Shingawa Kagawa
我想逐行阅读。
但是问题是方法hasNextLine块等待第三行之后的输入,因为键盘(System.in)的输入永远不会到达EOF。
现在,我如何通过按来达到EOF回车键?因为我不想告诉用户按下Ctrl + z来运行我的程序。
通常如何进行?有什么想法吗?
我正在寻找Java方面的解决方案,而不是控制台上的任何命令。
预先感谢
通常如何进行?:通常通过显示一个消息,并要求一些特殊单词完成输入。
public static void main( String [] args)引发IOException
{
扫描仪扫描程序= new Scanner(System.in);
字符串行;
System.out.println(输入名称(\ QUIT\完成));
而(scanner.hasNextLine()){
line = Scanner.nextLine();
if(line.equals( QUIT)){
休息;
}
}
// ...
}
在上面的示例中,使用的特殊单词是 QUIT
,当然您可以将其更改为更合适的一个。
Say I have the below code
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
//do something
}
And my input in the console is goes like this.
Wayne Rooney
Luis Nani
Shinji Kagawa
I want to read this line by line.
But the problem is the method hasNextLine blocks waiting for the input after the third line as the input from the keyboard (System.in) never reaches EOF.
Now, how do I reach EOF just by pressing enter key? because I don't want to tell the user to press the Ctrl+z to run my program.
How is it generally done? Any thoughts?
I am looking for a solution from the Java side and not any commands on the console.
Thanks in advance
How is it generally done?: It is usually done by showing a message to the user and requesting some special word to finish the input.
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(System.in);
String line;
System.out.println("Enter names (\"QUIT\" to finish)");
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.equals("QUIT")) {
break;
}
}
// ...
}
In the example above the special word used is "QUIT"
, of course you will change this to a more appropriated one.
这篇关于Java:如何在控制台程序中不使用Ctrl + Z的情况下使用scanner.hasNextLine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!