Question
You will make several changes to the program: 0) add a comment with your name to the top of the program 1) add code to
You will make several changes to the program:
0) add a comment with your name to the top of the program
1) add code to the program so that it counts the number of lines in the file that is read by the program
2) add code to the program so that it keep track of the longest line in the file (the line containing the most characters).
3) add code to the program to print the total number of lines and the number of characters in the longest line after the program displays the lines in the file.
NOTE: If you run your modified version of the program on the provided "address.txt" file, your program should report: The file contains 19 lines. The longest line contains 136 characters. NOTE: You should be able to run the program on other files and get correct results. For instance, you might try running the program on itself ("ReadFile.java").
This is what I have so far
import java.io.File; import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) { int count = 0;
try { // create a new file object File file = new File("Address.txt"); // create an object of Scanner // associated with the file Scanner sc = new Scanner(file);
// read each line and // count number of lines while(sc.hasNextLine()) { sc.nextLine(); count++; } System.out.println("Total Number of Lines: " + count);
// close scanner sc.close(); } catch (Exception e) { e.getStackTrace(); } Scanner fileInput = getInput(); while (fileInput.hasNextLine()) { String s = fileInput.nextLine(); System.out.println(s); } } public static String longestLine(String fileName) throws FileNotFoundException { Scanner sc = new Scanner(new File(fileName)); String result = ""; while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.length() > result.length()) { result = line; } System.out.println("Total Number of Lines: " + result);
} return result; } // page 425 of the textbook public static Scanner getInput () { Scanner console = new Scanner(System.in); // for keynoard input Scanner result = null; // for reading from a file while (result == null) { System.out.print("Please enter a filename : "); File someFile = new File(console.nextLine()); try { result = new Scanner(someFile); } catch (FileNotFoundException e) { System.out.println("File not found! Please try again."); } } return result; }
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started