Write a program that asks the user for name of file. The program should display
ID: 3906320 • Letter: W
Question
Write a program that asks the user for name of file. The program should display the number of words.
my error: Error: cannot find symbol
symbol: method tocountWord()
location: class java.lang.String
import java.io.*;
import java.util.Scanner;
public class WordCounter{
public static void main ( String [] args ) {
Scanner scanner = new Scanner( System.in );
String userFileName;
System.out.println( "Please enter the name of the file you want to read from. Please enter "count.txt"" );
userFileName = scanner.nextLine();
File file = new File ( userFileName );
while( !file.exists() ) {
System.out.println( userFileName + " does not exists. Please be sure to enter "count.txt"" );
userFileName= scanner.nextLine();
file = new File( userFileName );
}
Scanner fileToScan = new Scanner( file );
PrintWriter fileToWrite = new PrintWriter( "countToWordCounter.txt" );
while( fileToScan.hasNext() ){
fileToWrite.println( fileToScan.nextLine().tocountWord() );
}
System.out.println( " Count has been counted and converted to WordCounter.txt " );
fileToWrite.close();
fileToScan.close();
}
}
Explanation / Answer
Please find below the modified code.
CODE
=============
import java.io.*;
import java.util.Scanner;
public class WordCounter{
public static int tocountWord(String str) {
int count = 0;
for(char ch : str.toCharArray()) {
if(ch == ' ')
count ++;
}
return count + 1;
}
public static void main ( String [] args ) {
Scanner scanner = new Scanner( System.in );
String userFileName;
System.out.println( "Please enter the name of the file you want to read from. Please enter "count.txt"" );
userFileName = scanner.nextLine();
File file = new File ( userFileName );
while( !file.exists() ) {
System.out.println( userFileName + " does not exists. Please be sure to enter "count.txt"" );
userFileName= scanner.nextLine();
file = new File( userFileName );
}
Scanner fileToScan = null;
PrintWriter fileToWrite = null;
try {
fileToScan = new Scanner(file);
fileToWrite = new PrintWriter("countToWordCounter.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while( fileToScan.hasNext() ){
fileToWrite.println(tocountWord(fileToScan.next()));
}
System.out.println( " Count has been counted and converted to WordCounter.txt " );
fileToWrite.close();
fileToScan.close();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.