Good morning, I have written code that takes a txt file that is inputted and wil
ID: 3672747 • Letter: G
Question
Good morning,
I have written code that takes a txt file that is inputted and will basically output the information in the text file back to out the user. What I am trying to accomplish is writing code that will breakdown how many times every word appears on the code. Meaning that if in the text file the phrase "I love coding and coding loves me" I want to be able to output to the user "I -1, love-1, coding-2 and-1"....etc. I also want to use this program to be able to perform this task regardless of what the end user types in. Any help is greatly appreciated.
import java.io.*;
public class Wordy {
public static void main(String[] args){
try {
File fileDir = new File("c:\temp\wordy.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileDir), "UTF8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
Explanation / Answer
import java.io.*;
public class Wordy {
public static void main(String[] args){
try {
File fileDir = new File("c:\temp\wordy.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileDir), "UTF8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
StringTokenizer st=new StringTokenizer(str);
int n=st.countTokens( );
String a[]=new String[n];
int i=0,count=0;
while(st.hasMoreTokens())
{
a[i]=st.nextToken();
i++;
}
for(i=0;i<n;i++){
count=0;
for(int j=0;j<n;j++){
if(a[i].equals(a[j])){
count++;
}
System.out.print(a[i]+"-"+count+" ");
}
}
in.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.