Thao Nguyen
Thao Nguyen

Reputation: 901

Scanner in java STDIN nextLine()

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).

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.

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....

Upvotes: 1

Views: 24848

Answers (3)

user7279462
user7279462

Reputation: 23

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

Upvotes: 0

Amr Ali Alhossary
Amr Ali Alhossary

Reputation: 1

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).

Upvotes: 0

Joe K
Joe K

Reputation: 18434

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.

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

Upvotes: 1

Related Questions