Click here to Skip to main content
15,886,069 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I was tasked to write a program asks the user for the name of a file. The program should display the contents of the file with each line preceded witha line number followed by a colon. The line numbering should start at 1.

I got to the point of displaying the content in the file but I am not sure how to code for the line numbers and colons. Any suggestions?


Here is what I have so far:
import java.util.Scanner; // Needed for the Scanner class
import java.io.*;         // Needed for the File class

/**
   This program reads data from a file.
*/

public class LineNumbers
{
   public static void main(String[] args) throws IOException
   {
      // Create a Scanner object for keyboard input.
      Scanner keyboard = new Scanner(System.in);

      // Get the filename.
      System.out.print("Enter the filename: ");
      String filename = keyboard.nextLine();

      // Open the file.
      File file = new File(filename);
      Scanner inputFile = new Scanner(file);

      // Read lines from the file until no more are left.
      while (inputFile.hasNext())
      {
         // Read the next name.
         String familyName = inputFile.nextLine();
         
         // Display the last name read.
         System.out.println(familyName);
         
            }

      // Close the file.
      inputFile.close();
   }
}
Posted
Updated 22-Jan-10 10:06am
v2

You're a beginner therefore at some point recently you should have counted from 1 to 10 in a loop.

Fill in the blanks.
int lineNumber = 1;<br />while(....)<br />{<br />    ....<br />    System.out.println(lineNumber + ": " + ....);<br />    lineNumber++;<br />}


ps. Please put your code in <pre></pre> tags; as it makes it more readable. :)

 
Share this answer
 
I assume 'I was tasked' means that this is your homework. In that case, you should talk to your teacher if you get stuck, and you should assume your teacher knows how to use google, and will find out which of his students are asking for help online, so that if you turn in code you were given here, he will know about it.
 
Share this answer
 
Here is what you should do:
int lines = 1;
// Read lines from the file until no more are left.
while (inputFile.hasNext())
{
    // Read the next name.
    String familyName = inputFile.nextLine();

    // Display the last name read.
    System.out.println( lines + " " + familyName + ";" );
    lines++;
}

Netmani
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900