Hello, I am trying to create a Java program that reads a .txt file and outputs how many times the word "and" is used. I attempted modifying a code I had previously used for counting the total number of tokens, but now it is saying there is an input mismatch. Please help! My code is below:
import java.util.*;
import java.io.*;
public class Hamlet2
{
public static void main(String[] args) throws
FileNotFoundException
{
File file = new File("hamlet.txt");
Scanner fileRead = new Scanner(file);
int wordCount = 0;
while(fileRead.hasNext())
{
String word = fileRead.next("and");
wordCount++;
}
System.out.println("Total number of times \"and\" was used: " +
wordCount);
}
}
input code:
output:
code:
import java.util.*;
import java.io.*;
public class Hamlet2
{
public static void main(String[] args) throws
FileNotFoundException
{
/*make file Object*/
File file = new File("hamlet.txt");
/*read the file*/
Scanner fileRead = new Scanner(file);
/*declare the variables*/
int wordCount = 0;
String word="";
/*read line by line*/
while(fileRead.hasNextLine())
{
/*store input another Scanner Object*/
Scanner s2 = new Scanner(fileRead.nextLine());
/*read by words by words*/
while (s2.hasNext())
{
String s = s2.next();
/*if match increment couter*/
if(s.equals("and"))
{
wordCount++;
}
}
}
System.out.println("Total number of times \"and\" was used: " +
wordCount);
}
}
Get Answers For Free
Most questions answered within 1 hours.