Reputation: 2794
I am trying to count the number of times a string appears in a file. I want to find the number of times that "A, E, I, O, U" appears exactly in that order. Here is the text file:
AEIOU aeiou baeiboeu bbbaaaaaa beaeiou caeuoi ajejijoju aeioo aeiOu ma me mi mo mu take it OUT!
I want the method to then return how many times it is in the file. Any idea's on how I could go about doing this? The catch is I want to do this without using BufferedReader
. I can simply just read the file using Scanner
. Is there a way to do this?
I edited this and added the code I have so far. I don't think I am even close. I am pretty sure I need to use some nested loops to make this happen.
import java.util.*;
import java.io.*;
public class AEIOUCounter
{
public static final String DELIM = "\t";
public static void main(String[] args)
{
File filename = new File("aeiou.txt");
try
{
Scanner fileScanner = new Scanner(new File(filename));
while(fileScanner.hasNextLine())
{
System.out.println(fileScanner.nextLine());
}
}
catch(IOException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
fileScanner.close();
}
}
Upvotes: 1
Views: 94
Reputation: 311348
Smurf's answer is great. It's worth mentioning that if you're using Java 8, you can avoid using a Scanner
at all, and do this in a single expression:
long count = Files.lines(Paths.get("aeiou.txt"))
.flatMap(s -> Arrays.stream(s.split(" ")))
.filter(s -> s.equalsIgnoreCase("aeiou"))
.count();
Upvotes: 1
Reputation:
What you are doing now, is printing all the lines in the file.
fileScanner.hasNextLine()
fileScanner.nextLine()
But what you are looking for is filtering out separate words in the file:
Path path = Paths.get("/path/to/file");
Scanner sc = new Scanner(path);
int counter = 0;
while (sc.hasNext()) {
String word = sc.next();
if (word.equalsIgnoreCase("AEIOU")) {
counter += 1;
}
}
System.out.print("Number of words: " + counter);
Upvotes: 1