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

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

ID: 3821502 • Letter: P

Question

Part 2.

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.  

I have the code to read my file but I am not sure where to put my file in the documents so that when the code runs it reads it. I am using eclipse on a mac.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

package readFile;

import java.io.File;

import java.util.Scanner;

import java.util.StringTokenizer;

public class Strings {

   public static void main(String[] args) {

   Scanner txtscan;

   try {

   txtscan = new Scanner(new File("D:\abc.txt"));

   int totCount = 0;

   while(txtscan.hasNextLine()){

   String str = txtscan.nextLine();

   StringTokenizer stringTokenizer = new StringTokenizer(str, " ");

   while (stringTokenizer.hasMoreElements()) {

   totCount++;

   stringTokenizer.nextElement();

   }

   }

  

   System.out.println("Number of words in the file are : "+totCount);

   } catch (Exception e) {

   e.printStackTrace();

   }

   }

Problems (a Javadoc Declaration B Console 23 minated> Strings U Application] Library/Java/JavaVirtualMachines /jdkl.8.0_65jdk/Contents, /Home/bin/java (Apr 19, 2017, 8:36:30 PM) ava

Explanation / Answer

/*
Go inside eclipse workspace where all the packages are kept.
The abc.txt file needs to be kept
just inside the package folder (package here is readFile)
beside bin and src.
*/

package readFile;
import java.io.File;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Strings {

public static void main(String[] args) {
Scanner txtscan;
try {
// file path just inside the package folder
txtscan = new Scanner(new File("abc.txt"));

int totCount = 0;

while(txtscan.hasNextLine()){

String str = txtscan.nextLine();

StringTokenizer stringTokenizer = new StringTokenizer(str, " ");

while (stringTokenizer.hasMoreElements()) {
totCount++;
stringTokenizer.nextElement();
}
}
  
System.out.println("Number of words in the file are : "+totCount);

} catch (Exception e) {
e.printStackTrace();
}

}

}


/*
abc.txt
my name is james anderson
I live in england
I play for whales county

output:

Number of words in the file are : 14

*/