Neils Medereck
Neils Medereck

Reputation: 29

How can I display file with line numbers in my Java program?

I want my program to display the contents of the file the user inputs with each line preceded with a line number followed by a colon. The line numbering should start at 1.

This is my program so far:

import java.util.*;
import java.io.*;

public class USERTEST {
   public static void main(String[] args) throws IOException
   {
   Scanner keyboard = new Scanner(System.in);
   System.out.print("Enter a file name: ");
   String filename = keyboard.nextLine();

   File file = new File(filename);
   Scanner inputFile = new Scanner(file);
   String line = inputFile.nextLine();

   while (inputFile.hasNext()){
   String name = inputFile.nextLine();

   System.out.println(name);
   }

   inputFile.close();

   }

}

I can display the contents of the file so far, but I don't know how to display the contents with the line numbers.

Upvotes: 0

Views: 7974

Answers (5)

MeshBoy
MeshBoy

Reputation: 692

int lineNumber=0;

while (inputFile.hasNext()){

String name = inputFile.nextLine();

`System.out.println(lineNumber+ ":"+name);`

linenumber++;

}

Upvotes: 0

drusilabs
drusilabs

Reputation: 133

You just need to concat an index to your output string.

  int i=1;
  while (inputFile.hasNext()){
  String name = inputFile.nextLine();

    System.out.println(i+ ","+name);
    i++;
  } 

Upvotes: 1

Z .
Z .

Reputation: 12837

Integer i = 0;
while (inputFile.hasNext()) {
    i++;
    String line = inputFile.nextLine();
    System.out.println(i.toString() + ": " + line);
}

Upvotes: 2

GhostCat
GhostCat

Reputation: 140447

What about creating a numerical counter (increased every time you read a line) ... and putting that in front of the string that you are printing?

Upvotes: 0

PandaConda
PandaConda

Reputation: 3506

Use an int initialized to 1 and increment it every time you read a line, then just output it before the line contents.

Upvotes: 0

Related Questions