java - Keep Track of Current Line Being Scanned -


I am using a scanner to scan input from a command prompt, and I have a special word that On should keep track of the line. If I enter these inputs through the command:

"first line

now the second line

finally the last line"

< P> word: line: 1

word: line now: i

I want to print it:

"word: first line: 1

2

<

Word at end row: 3

Word last line: 3

Word: second line: 2

Word line line: 3 "

This is my code:

  public static zero main (string [] Args) {Scanner Scan = New Scanner (System.in); Int Linnum = 1; While (scan.hasNext ()) {if (scan.next (). Matches ("[\\ n]") lineNum ++; System.out.println ("Word:" + scan.next () + "Line : "I have tried many different regex patters, but I have tried that no trick has been tried. I have tried some other ways to increase increment like counter. Scan hasNextLine But there is no success and I think it should be a very easy way of doing this, I am not searching for it.   

A And I understand your question, so yes, you can do this by reading each line and then dividing words in line with some words

  scanner scan = new scanner (system .in); int linenum = 1; while (scanned.henextLine ()) {string line = scanned.Nextin (); string [] word = line. String for word split ("\\ s +"); word: word } {System.out.printf ("word:% s line:% d% n", word, linename);} linename ++; // <- then increment line count}  

Comments