Question: I'm trying to write this program in java that reads in a file, and takes all the words in the file adds each word to

I'm trying to write this program in java that reads in a file, and takes all the words in the file adds each word to a map as the key(string) portion, removes punctionation and turns them to lowercase, and then prints to the outfile the keys and occurances(integer) of each key. here's my code so far. Everything currently works except counting the occurances correctly.

heres the code so far

import java.util.Scanner;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

public class Suess2 {

public static boolean isLetter(char c) {

if ((c >= 'a' && c <= 'z' ) || (c >= 'A' && c <= 'Z')) {

return true;

}

else

return false;

}

public static String removePunc (String s){

String newStr = "";

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

char c = s.charAt(i);

if(isLetter(c)) {

newStr += c;

}

}

return newStr;

}

public static void main (String [ ] args) {

// open the file

Scanner console = new Scanner(System.in);

String fileName = "/Users/*myname*/Desktop/greeneggs.txt";

try { Scanner input = new Scanner(new File(fileName));

Map words = new LinkedMap();

int occurance = 0;

while (input.hasNext()) {

String next = input.next().toLowerCase();

if (!words.containsKey(next)) {

words.add(removePunc(next),1);

}

if (words.containsKey(next)) {

occurance++;

words.add(next, occurance);

}

}

System.out.println("Total words = " + words.size());

Scanner infile = new Scanner(new File ("/Users/*myname*/Desktop/infile.txt"));

PrintWriter outFile = new PrintWriter ("/Users/*myname*/Desktop/outfile.txt");

// read and write data

outFile.print(words.toString() + "");

// close files

infile.close();

outFile.close();

}

catch (FileNotFoundException e)

{

System.out.println(e.getMessage());

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!