Question

In: Computer Science

Hello! I am having trouble starting this program in Java. the objective is as follows: "...

Hello! I am having trouble starting this program in Java.

the objective is as follows:

" I will include a text file with this assignment. It is a text version of this assignment.

Write a program that will read the file line by line, and break each line into an array of words using the tokenize method in the String class. Count how many words are in the file and print out that number. "

my question is, how do i start this program? I know i can use the following snippet of code to read the text line by line,

BufferedReader reader = new BufferedReader(new StringReader(<string>));
reader.readLine();

but, I am unsure how to actually use the tokenize class, I am using the book intro to Java prog by Liang but i am not seeing an example similar that calls for the txt to be read and to count and print them.

Solutions

Expert Solution

Java Program:

/* Java Program that reads data from file and counts number of words in the file using String tokenizer class */

import java.io.*;
import java.util.*;

//Class definition
class StringTokenizerDemo
{
   //Main method
   public static void main(String[]args) throws IOException
   {
       String line;
       int words = 0;
      
       //Opening file for reading
       FileReader fin = new FileReader("inputFile.txt");
      
       //Reader class to read data from file
       BufferedReader reader = new BufferedReader(fin);

       //Iterate till all lines are processed
       while ( ( line = reader.readLine() ) != null )
       {
           //Tokenizing line into words using space delimiter
           StringTokenizer st = new StringTokenizer(line," ");

           //Counting number of words in the line
           while (st.hasMoreTokens())
           {
               //Getting next token
               st.nextToken();
              
               //Incrementing number of words
               words += 1;
           }
       }
      
       //Closing file
       fin.close();
      
       //Printing number of words
       System.out.println("\n\n Total number of words in the file: " + words);
   }
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

Sample Output:


Related Solutions

I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
Hello, I am having trouble getting started on my project and building these functions. How do...
Hello, I am having trouble getting started on my project and building these functions. How do I build a function that continuously adds new "slices" to the list if they are below/above the size limit? I didn't copy the entire problem, but just for reference, when the code is run it will take user input for size limit (L), time cost for a random slice(R), and time cost for an accurate slice(A). Question: In real life, a steak is a...
Hello, I am having trouble with my Advanced Accounting Ch 18 homework. Accounting for nonprofts. Here...
Hello, I am having trouble with my Advanced Accounting Ch 18 homework. Accounting for nonprofts. Here are a few questions: At the beginning of the year, Nutrition Now, a health and welfare not-for-profit entity, had the following equity balances: Net assets without donor restriction $400,000 Net assets with donor restriction $290,000 1. Unrestricted contributions (pledges) of $250,000, to be collected in cash in thirty days, before the end of the year, are received. 2. Salaries of $27,000 are paid with...
I was able to calculate (a) but I am having trouble with the calculations of (b)....
I was able to calculate (a) but I am having trouble with the calculations of (b). Thanks! The following are New York closing rates for A$/US$ and $/£:                                     A$/$ = 1.5150;               $/£ = $1.2950             (a) Calculate the cross rate for £ in terms of A$ (A$/£).             (b) If £ is trading at A$1.95/£ in London (cross market) on the same day, is there an arbitrage opportunity?  If so, show how arbitrageurs with £ could profit from this opportunity and calculate the arbitrage...
I am having an issue with the Java program with a tic tac toe. it isn't...
I am having an issue with the Java program with a tic tac toe. it isn't a game. user puts in the array and it prints out this. 1. Write a method print that will take a two dimensional character array as input, and print the content of the array. This two dimensional character array represents a Tic Tac Toe game. 2. Write a main method that creates several arrays and calls the print method. Below is an example of...
Having some trouble with this Java Lab (Array.java) Objective: This lab is designed to create an...
Having some trouble with this Java Lab (Array.java) Objective: This lab is designed to create an array of variable length and insert unique numbers into it. The tasks in this lab include: Create and Initialize an integer array Create an add method to insert a unique number into the list Use the break command to exit a loop Create a toString method to display the elements of the array Task 1: Create a class called Array, which contains an integer...
I am working through this solution in rstudio and am having trouble fitting this table into...
I am working through this solution in rstudio and am having trouble fitting this table into a linear regression analysis. an answer with corrosponding r code used would be greatly appreciated A study was conducted to determine whether the final grade of a student in an introductory psychology course is linearly related to his or her performance on the verbal ability test administered before college entrance. The verbal scores and final grades for all 1010 students in the class are...
I am having the most trouble with 1d: 1. a. Prove that if f : A...
I am having the most trouble with 1d: 1. a. Prove that if f : A → B, g : B → C, and g ◦f : A → C is a 1-to-1 surjection, then f is 1-to-1 and g is a surjection. Proof. b. Prove that if f : A → B, g : B → C, g ◦ f : A → C is a 1-to-1 surjection, and g is 1-to-1, then f is a surjection. Proof. c....
I am working on these study questions and am having trouble understanding how it all works...
I am working on these study questions and am having trouble understanding how it all works together. Any help would be greatly appreciated!! An all equity firm is expected to generate perpetual EBIT of $50 million per year forever. The corporate tax rate is 0% in a fantasy no tax world. The firm has an unlevered (asset or EV) Beta of 1.0. The risk-free rate is 5% and the market risk premium is 6%. The number of outstanding shares is...
Java ArrayList Parking Ticket Simulator, Hello I am stuck on this problem where I am asked...
Java ArrayList Parking Ticket Simulator, Hello I am stuck on this problem where I am asked to calculate the sum of all fines in the policeOfficer class from the arraylist i created. I modified the issueParking ticket method which i bolded at the very end to add each issued Parking ticket to the arrayList, i think thats the right way? if not please let me know. What I dont understand how to do is access the fineAmountInCAD from the arrayList...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT