java STDIN nextLine() 中的扫描仪

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12468193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:01:14  来源:igfitidea点击:

Scanner in java STDIN nextLine()

javajava.util.scanner

提问by Thao Nguyen

Our professor has us doing a lab to parse strings. He refuses to let us use files and says if he copy and paste a paragraph of strings we have to parse it. My problem is I'm not sure how to get the data from STD when copy and paste (I could do this with a file much easier).

我们的教授让我们做一个实验室来解析字符串。他拒绝让我们使用文件,并说如果他复制并粘贴一段字符串,我们必须对其进行解析。我的问题是我不确定在复制和粘贴时如何从 STD 获取数据(我可以更轻松地使用文件来完成此操作)。

public static void main(String[] args)
  {
    Scanner finput;
    String input;
    System.out.println("Enter Data: ");
    finput = new Scanner(System.in);

    input = finput.nextLine();
            System.out.println("OUTPUT")
    System.out.println(input);
    System.out.println(input.length());
    while(finput.hasNextLine())
    {
        input = finput.nextLine();
        System.out.println(input);
    }
  }

This is what I got so far my only problem is when I Copy and paste a paragraph into the console (using eclipse) it will not grab the last line unless I hit enter. If I type something again and press enter the previous line is concatenated with the new entry like below.

这是我到目前为止得到的唯一问题是当我将一个段落复制并粘贴到控制台(使用 eclipse)时,除非我按 Enter,否则它不会抓取最后一行。如果我再次输入内容并按回车键,则前一行将与如下所示的新条目连接。

Enter Data:
FirstLine
SecondLineOUTPUT
FirstLine
junk
SecondLinejunk

If the input was just single line by line I wouldn't be having this problem and I'm also not sure why if I copy paste it doesn't require me to hit enter to progress....

如果输入只是一行一行的,我就不会遇到这个问题,而且我也不确定为什么如果我复制粘贴它不需要我按 Enter 键继续前进....

回答by Joe K

There's no way to do what you're thinking, as the input stream has no way of knowing what the "end" of the line is unless you press enter.

没有办法按照你的想法去做,因为输入流无法知道行的“结束”是什么,除非你按下回车键。

Consider if you were to type in the text:

考虑是否要输入文本:

ABCD
EFGH

But you really just meant for the second line to be EFG, not EFGH. How would there possibly be a way to determine that? Copy+paste is exactly like actually typing, just much faster.

但你真的只是想为第二行,而EFG不是EFGH。怎么可能有一种方法来确定呢?复制+粘贴与实际打字完全一样,只是速度要快得多。

I'm guessing your professor will be hitting the enter key at the end of the paragraph for you.

我猜你的教授会为你按下段落末尾的回车键。

回答by Amr Ali Alhossary

You just need to tell the console that you finished the input, by sending EOF character (CTRL+D in Unix/Linux, or CTRL+Z in Windows).

您只需要通过发送 EOF 字符(在 Unix/Linux 中为 CTRL+D,或在 Windows 中为 CTRL+Z)来告诉控制台您已完成输入。

回答by user7279462

Just while you are copying.. copy one more white space which will act as an enter!!

就在您复制时.. 再复制一个空格,作为输入!!