patternjavaMinor
Counts the number of times a particular character, such as e, appears in a file
Viewed 0 times
suchnumberthefileparticularcharacterappearstimescounts
Problem
This question came from a Java tutorial online:
Write an example that counts the number of times a particular character, such as e, appears in a file.
I was just wondering if there is any way to improve this particular solution.
Write an example that counts the number of times a particular character, such as e, appears in a file.
I was just wondering if there is any way to improve this particular solution.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CountLetter{
public static void main(String[] args) {
Path file = Paths.get("/Users/justin/Desktop/Codes Netbean/JavaRandom/xanadu.txt");
CountLetter cl1 = new CountLetter(file, 'e');
System.out.println(cl1.count());
}
private Path file;
private char lookFor;
CountLetter(Path file, char lookFor){
this.file = file;
this.lookFor = lookFor;
}
private int count(){
int count = 0;
try(BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(file)))){
String line = null;
while((line = br.readLine()) != null){
for(int i = 0; i < line.length(); i++){
if(line.charAt(i) == lookFor){
count++;
}
}
}
} catch (IOException x){
System.err.println(x);
}
return count;
}
}Solution
If you are using java 8 you can use streams.
Also IMO for this kind of functionality a static method would me more appropriate.
Also IMO for this kind of functionality a static method would me more appropriate.
public static long countCharacter(Path path, char lookFor) throws IOException {
try (Stream stream = Files.lines(path)) {
return stream.flatMapToInt(String::chars)
.filter(c -> c == (int) lookFor)
.count();
}
}Code Snippets
public static long countCharacter(Path path, char lookFor) throws IOException {
try (Stream<String> stream = Files.lines(path)) {
return stream.flatMapToInt(String::chars)
.filter(c -> c == (int) lookFor)
.count();
}
}Context
StackExchange Code Review Q#119834, answer score: 4
Revisions (0)
No revisions yet.