Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

this code prints line numbers in front of lines in a text input file, i need to

ID: 3673201 • Letter: T

Question

this code prints line numbers in front of lines in a text input file, i need to make it skip blank lines

import java.util.*;

// class
public class LineNumbers
{
// main method
public static void main(String[] args)
{
// string to store filename
String fileName;
// Scanner object to read from console
Scanner sc = new Scanner(System.in);
// ask use for filename
System.out.print("Enter the file name to read : ");
// read filename
fileName = sc.nextLine();
// open file using buffered reader
try {BufferedReader br = new BufferedReader(new FileReader(fileName));

{
String sCurrentLine;
int line = 0;
// read line by line
while ((sCurrentLine = br.readLine()) != null)
{
line++;
// print line number with 3 spaces width
System.out.printf("%3d",line);
// print line
System.out.println(". " + sCurrentLine);
}
}
  
{br.close();
}
}

// catch exception if not able to open file
catch (IOException e)
{
e.printStackTrace();
}


}
}

Explanation / Answer

Here is the code

import java.util.*;
import java.io.*;
// class
public class LineNumbers
{
// main method
public static void main(String[] args)
{
// string to store filename
String fileName;
// Scanner object to read from console
Scanner sc = new Scanner(System.in);
// ask use for filename
System.out.print("Enter the file name to read : ");
// read filename
fileName = sc.nextLine();
// open file using buffered reader
try {BufferedReader br = new BufferedReader(new FileReader(fileName));

{
String sCurrentLine;
int line = 0;
// read line by line
while ((sCurrentLine = br.readLine()) != null)
{
// Trim the string to remove leading and trailing spaces and then check if the string is empty or not
if(!sCurrentLine.trim().isEmpty())
{
line++;
// print line number with 3 spaces width
System.out.printf("%3d",line);
// print line
System.out.println(". " + sCurrentLine);
}
}
}
  
{br.close();
}
}

// catch exception if not able to open file
catch (IOException e)
{
e.printStackTrace();
}


}
}