Homework Help Question & Answers

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 include , ! . ; : ? & # and $.

Then test your method with the data file.

This is my code so far and I could use lots of help and explanations to make this work

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class WordCount{

   public static void main(String[] args){
      File file = new File(args[0]);
      System.out.println("File name is: "+file);
      String word = "";
             
    
    
    
   }
   public static int countWord(String word, File file){
      int counter =0;
      try{
         BufferedReader b = new BufferedReader(new FileReader(file));
         while((readLine=b.readLine())!=null){
            for(String s: readLine.split(" ")){
               if(s.toLowerCase()==word.toLowerCase()){
                  count++;
             
               }
            }
         }
      
      }catch(IOException e){
         System.out.println("errors");
      }
      System.out.println("count is: " +count);
      return count;


   }


   public static int countWord(String word, String str){
      int count =0;
      Scanner sc = new Scanner(str.toLowerCase());
      word=word.toLowerCase();
      for (int i = 0; i < str.length(); i++) {
         while(sc.hasNext()){
            String temp = sc.hasNext();
            if(temp=="word") count++;
            System.out.println("Current or next line: "+sc.hasNext());
         }
    
      }

      return count;

   }

}

0 0
Add a comment
Answer #1

I would like you to modify code as follows:

Instead of taking list of arguments take just filename as argument.

If you need to find the word count from file then the function would be called accordingly.

To get this calculate the no.of arguments.

Also you can take the word whose count is to be found through the argument.

If arguments length is 2 then consider filename is also included otherwise only word is given as argument

Also you need to read the string and pass it as argument to the function but not read it from within the function.

//java code

mport java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class WordCount{

   public static void main(String[] args){

int no_arg = args.length();

if(length==2){
      File file = new File(args[0]);
      System.out.println("File name is: "+file);


      String word = args[1];

System.out.println("The word count is" + countWord(word,file));

}

else

{

String word=args[0];

//read string

StringBuilder everything = new StringBuilder();
    String line;
BufferedReader buffIn = new BufferedReader(System.in);
    while( (line = buffIn.readLine()) != null) {
       everything.append(line);
    }

String str=new String(everything);

System.out.println("The word count is " + wordCount(word,str));
}


             
    
    
    
   }
   public static int countWord(String word, File file){
      int counter =0;
      try{
         BufferedReader b = new BufferedReader(new FileReader(file));
         while((readLine=b.readLine())!=null){
            for(String s: readLine.split(" ")){
               if(s.toLowerCase()==word.toLowerCase()){
                  count++;
             
               }
            }
         }
      
      }catch(IOException e){
         System.out.println("errors");
      }
      System.out.println("count is: " +count);
      return count;


   }


   public static int countWord(String word, String str){
      int count =0;

Scanner sc = new Scanner(str.toLowerCase());
      word=word.toLowerCase();
      for (int i = 0; i < str.length(); i++) {
         while(sc.hasNext()){
            String temp = sc.hasNext();
            if(temp=="word") count++;
            System.out.println("Current or next line: "+sc.hasNext());



    
      }

      return count;

   }

}

As we are taking input as multiple lines we can use simple word count function for string

But you need to replace all \n with " "(space)

static int countOccurences(String str, String word)

{

    // split the string by spaces in a

    String a[] = str.split(" ");

  

    // search for pattern in a

    int count = 0;

    for (int i = 0; i < a.length; i++)

    {

    // if match found increase count

    if (word.equals(a[i]))

        count++;

    }

  

    return count;

}

Add a comment
Know the answer?
Add Answer to:
Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Wr...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coin

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
  • 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...

  • 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...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • I need help writing this code for java class. Starter file: Project3.java and input file: dictionary.txt...

    I need help writing this code for java class. Starter file: Project3.java and input file: dictionary.txt Project#3 is an extension of the concepts and tasks of Lab#3. You will again read the dictionary file and resize the array as needed to store the words. Project#3 will require you to update a frequency counter of word lengths every time a word is read from the dictionary into the wordList. When your program is finished this histogram array will contain the following:...

  • I need help understanding this programming assignment. I do not understand it at all. Someone provided...

    I need help understanding this programming assignment. I do not understand it at all. Someone provided me with the code but when I run the code on eclipse it gives an error. Please explain this assignment to me please. Here is the code: import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class TextEditor { public static List<String> lines = new ArrayList<String>(); public static void main(String[] args) throws IOException { Scanner s = new...

  • Trying to test if two words are anagrams- Java Program

    Hello,I'm trying to write a code to check if two strings are anagrams. i have already figured out a code but I can't get it to work for words of different cases and wordswith whitespace. I would really appreciate any inputThank you!Here is what I have so farimport java.io.*;public class AnagramFinder{public static boolean anagram(String a, String b){if (a.length() != b.length()) return false;int[] alphanum = new int[256];int chars = 0; //no of unique charactersint num_completed_b = 0;char[] a_array = a.toCharArray();for (char...

  • Java only. Thanks These questions involve choosing the right abstraction (Collection, Set, List, Queue, Deque, SortedSet,...

    Java only. Thanks These questions involve choosing the right abstraction (Collection, Set, List, Queue, Deque, SortedSet, Map, or SortedMap) to EFFICIENTLY accomplish the task at hand. The best way to do these is to read the question and then think about what type of Collection is best to use to solve it. There are only a few lines of code you need to write to solve each of them. Unless specified otherwise, sorted order refers to the natural sorted order...

  • 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...

  • Java File

    In JavaCreate a file using any word processing program or text editor.Write an application that displays the file's name, containingfolder size and time of last modification.Save as FileStatisticsThis is what I have with errors, am i going down the right path?Thanks<code>import java.nio.file.*;import java.io.*;import java.nio.file.attribute.*;import java.util.Scanner;public class FileStatistics{private static Object Attributes;public static void main(String[] args){Scanner kb = new Scanner(System.in);String filename;System.out.print("Enter name of file to use>>");filename = kb.nextLine();String fileName = "C:\Java\FileStatistics.txt";Path file = Paths.get(fileName);Paths.get("C:\Java\FileStatistics.txt");String s = "ABCDF";byte[] data = s.getBytes();OutputStream output =...

  • 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...

Free Homework 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.