Question

Ask the user for the name of a file and a word. Using the FileStats class,...

Ask the user for the name of a file and a word. Using the FileStats class, show how many lines the file has and how many lines contain the text.

Standard Input                 Files in the same directory
romeo-and-juliet.txt
the
  • romeo-and-juliet.txt

Required Output

Enter a filename\n
romeo-and-juliet.txt has 5268 lines\n
Enter some text\n
1137 line(s) contain "the"\n

Your Program's Output

Enter a filename\n
romeo-and-juliet.txt has 5268 lines\n
Enter some text\n
553 line(s) contain "the"\n
 (Your output is too short.)

My Code:

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class FileStats
{
    public static void main(String[] args) throws Exception
    {
        Scanner input=new Scanner(System.in);
        System.out.println("Enter a filename");
        String file_name=input.nextLine();


        int word_line_count=0,line_count=0;
        String search_word=input.nextLine();
        File f=new File(file_name);
        String[] words_sentence;
        FileReader file_object = new FileReader(file_name);
        BufferedReader buffer = new BufferedReader(file_object);
        String sentence;

        while((sentence=buffer.readLine())!=null)
        {
            words_sentence=sentence.split(" ");
            for (String word : words_sentence)
            {
                if (word.equals(search_word))
                {
                    word_line_count++;
                    break;
                }
            }
            line_count++;
        }

        System.out.println(file_name + " has " + line_count + " lines");

        System.out.println("Enter some text");

        System.out.println(word_line_count + " line(s) contain " + '\u0022' + search_word + '\u0022');
        file_object.close();
    }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileStats {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("Enter a filename");
  
String file_name = input.nextLine();
int word_line_count = 0, line_count = 0;
  
  
File file = new File(file_name);
FileInputStream fin = new FileInputStream(file);
BufferedReader buffer = new BufferedReader(new InputStreamReader(fin));
String sentence;
  
while ((sentence = buffer.readLine()) != null) {
line_count++;
}
System.out.println(file_name + " has " + line_count + " lines");

fin.getChannel().position(0);
System.out.println("Enter some text");
String search_word = input.nextLine();
  
while ((sentence = buffer.readLine()) != null) {
if(sentence.toLowerCase().contains(search_word.toLowerCase())){
   word_line_count++;
}
}
  
System.out.println(word_line_count + " line(s) contain " + '\u0022' + search_word + '\u0022');
buffer.close();
input.close();
}
}


answered by: ANURANJAN SARSAM
Add a comment
Answer #2

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileStats {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("Enter a filename");
  
String file_name = input.nextLine();
int word_line_count = 0, line_count = 0;
  
  
File file = new File(file_name);
FileInputStream fin = new FileInputStream(file);
BufferedReader buffer = new BufferedReader(new InputStreamReader(fin));
String sentence;
  
while ((sentence = buffer.readLine()) != null) {
line_count++;
}
System.out.println(file_name + " has " + line_count + " lines");

fin.getChannel().position(0);
System.out.println("Enter some text");
String search_word = input.nextLine();
  
while ((sentence = buffer.readLine()) != null) {
if(sentence.toLowerCase().contains(search_word.toLowerCase())){
   word_line_count++;
}
}
  
System.out.println(word_line_count + " line(s) contain " + '\u0022' + search_word + '\u0022');
buffer.close();
input.close();
}
}

Add a comment
Know the answer?
Add Answer to:
Ask the user for the name of a file and a word. Using the FileStats class,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Java Programming chapter 6 Make a class that represents a file. This class will have...

    In Java Programming chapter 6 Make a class that represents a file. This class will have the ability to calculate the number of lines in that file and the ability to search through the file. UML diagram: -filename:String +FileStats(String fname) +getNumMatchingWords(String wordtoFind) : int +getNumLines() : int The getNumMatchingWords method will take a bit of text and determine how many lines contain that text. Make the comparison not care about case. View required output Test Case 1 Files in the...

  • Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Wr...

    Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Write a program named WordCount.java, in this program, implement two static methods as specified below: public static int countWord(Sting word, String str) this method counts the number of occurrence of the word in the String (str) public static int countWord(String word, File file) This method counts the number of occurrence of the word in the file. Ignore case in the word. Possible punctuation and symbals in the file...

  • composed the following java code to read a string from a text file but receiving compiling...

    composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main {   public static void main(String[] args) {     System.out.print("Enter the...

  • package Lab11; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Lab10 {    public...

    package Lab11; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Lab10 {    public static void main (String [] args)    {    // ============================================================    // Step 2. Declaring Variables You Need    // These constants are used to define 2D array and loop conditions    final int NUM_ROWS = 4;    final int NUM_COLS = 3;            String filename = "Input.txt";    // A String variable used to save the lines read from input...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • Step 1: Getting Started Create a new .java file named Lab12.java. At the beginning of this...

    Step 1: Getting Started Create a new .java file named Lab12.java. At the beginning of this file, include your assignment documentation code block. After the documentation block, you will need several import statements. import java.util.Scanner; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; Next, declare the Lab12 class and define the main function. public class Lab12 { public static void main (String [] args) { Step 2: Declaring Variables For this section of the lab, you will need to declare...

  • Please help me fix my errors. I would like to read and write the text file...

    Please help me fix my errors. I would like to read and write the text file in java. my function part do not have errors. below is my code import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.FileWriter; import java.io.IOException; public class LinkedList {    Node head;    class Node    {        int data;        Node next;       Node(int d)        {            data = d;            next = null;        }    }    void printMiddle()    {        Node slow_ptr...

  • *JAVA Prompt the user for a movie name. Output the three movies that come alphabetically before...

    *JAVA Prompt the user for a movie name. Output the three movies that come alphabetically before the one entered. I need help correcting my code. I'm unsure why I am getting a name, year, and genre in my output. Input: Jericho Output: Similar title finder. Enter a movie name.\n Here are the 3 movies that are listed before the one you entered\n Jeremy Paxman Interviews...\n Jeremy Taylor\n Jeremy Vine Meets...\n Current output: Similar title finder. Enter a movie name.\n Here...

  • 1. Copy the file secret.txt into a path that you can access. Read FilePath.doc if you...

    1. Copy the file secret.txt into a path that you can access. Read FilePath.doc if you have questions on file path. Copy SecretMessage.java into your NetBeans or other IDE tools. 2. Finish the main method that will read the file secret.txt, separate it into word tokens.You should process the tokens by taking the first letter of every fifth word, starting with the first word in the file. These letters should converted to capitals, then be appended to StringBuffer object to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT