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

Write a program that counts the number of words and characters (excluding spaces

ID: 3817718 • Letter: W

Question

Write a program that counts the number of words and characters (excluding spaces) in a given text file. A skeleton of the program, as well as the code for defining a scanner object that reads from a text file, is provided

has to be written in java

// skeleton file
import java.io.*;
import java.util.Scanner;

public class CountWords {
public static void main(String[] args) throws IOException {
  
File inFile = new File("CountWordsTestFile.txt");
Scanner input = new Scanner(inFile);
  
// Your code here
  
  
  
input.close();
}
}

Explanation / Answer

program:-

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

public class CountWords
{
    public static void main(String[] args) throws IOException
    {
        File inFile = new File("E:/Java/CountWordsTestFile.txt");
        try (Scanner input = new Scanner(inFile))
        {
            int wcount=0,chrcount=0;    //chrcount for number of characters wcount for number of words
            String s;
            while(input.hasNext())      //checks if strings are available
            {
                wcount++;           //if available increment string
                s=input.next();     //get that string to s
                chrcount+=s.length();   //add that string length to chrcount
            }
            System.out.println("Number of words: " + wcount);       //print word count
            System.out.println("Number of characters: " + chrcount);    //print characters count
            input.close();
        }
        catch(IOException e)    //handel ioexceptions
        {
            System.out.println(e);
        }
    }
}

output:-

run:
Number of words: 12
Number of words: 53
BUILD SUCCESSFUL (total time: 0 seconds)

text file i have given for input is

E:/Java/CountWordsTestFile.txt:-

When you build an Java application project that has a main class

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote