-1

I have a file that looks like follows:

image

What I need is to read only names (first column) and output it.

  while (sc.hasNext()) 
     System.out.println(sc.next()); 

Another solution I tried is:

  while (sc.hasNextLine()) 
     System.out.println(sc.nextLine()); 

The ones that are above obviously don't work. I am stuck and don't know what to do. I was trying to google my problem but couldn't find the answer.

nishantc1527
  • 376
  • 1
  • 12
martines
  • 47
  • 6
  • Read the line into a variable then split on space `str.split("\\s+")` and print the column you're interested in: https://repl.it/repls/TestySeashellFibonacci – Nir Alfasi Aug 14 '19 at 23:16

1 Answers1

1
while(sc.hasNextLine()) {
    StringBuilder toPrint = new StringBuilder();
    String line = sc.nextLine();

    for(int i = 0; i < line.length() && line.charAt(i) != ' '; i ++) {
        toPrint.append(line.charAt(i));
    }

    System.out.println(toPrint.toString());
}

The reason I don't use String.split() is because that does lot's of unnecessary work, as it splits the entire string, and you only want the first word.

nishantc1527
  • 376
  • 1
  • 12