람다 구문을 사용하는 자바 스트림을 사용하는 과제를 진행하고 있습니다. 프로그램이 설계되어 있어야합니다 (1) 파일 세트를 계산하려면 (2) 해당 파일 내의 단어를 계산하려면 (3) 결과를 인쇄하고 표시하십시오.자바 8 파일/워드 카운팅 프로그램의 이상한 출력
Count 11 files:
word length: 1 ==> 80
word length: 2 ==> 321
word length: 3 ==> 643
.....
그러나, 내가 대신이 출력을 받고 있어요 : - FileCatch
, 파일과를 계산
primes.txt
word length: 1 ==> [email protected]
constitution.txt
word length: 2 ==> [email protected]
short.txt
word length: 3 ==> [email protected]
.....
Count: 11 files
내가 작성한 프로그램은 두 개의 클래스에이 출력의 예입니다 WordCount
, 이는 단어를 계산합니다 (이론적으로). 누구든지 도움이되는 프로그래밍 팁이 있다면, 나는 인정 될 것이다.
FileCatch
클래스
public class FileCatch8 {
public static void main(String args[]) {
List<String> fileNames = new ArrayList<>();
try {
DirectoryStream<Path> directoryStream = Files.newDirectoryStream
(Paths.get("files"));
int fileCounter = 0;
for (Path path : directoryStream) {
System.out.println(path.getFileName());
fileCounter++;
fileNames.add(path.getFileName().toString());
WordCount WordCnt = new WordCount();
System.out.println("word length: " + fileCounter + " ==> " + WordCnt);
}
}catch(IOException ex){
}
System.out.println("Count: "+fileNames.size()+ " files");
}
}
WordCount
클래스 :
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import java.util.stream.Stream;
/**
*
* @author GeraldShields
*/
public class WordCount {
/**
*
* @return
* @throws IOException
*/
public Map<String, Long> WordCount()throws IOException {
Stream<String> lines = Files.lines(Paths.get("constitution.txt"));
Map<String, Long> wordMap = lines
.parallel()
.map(String::toLowerCase)
.map(line -> line.split("\\W+"))
.flatMap(line -> Arrays.asList(line).stream())
.filter(word -> !word.matches("\\d+") && word.trim().length() != 0)
.map(word -> new SimpleEntry<>(word, 1))
.collect(groupingBy(SimpleEntry::getKey, counting()));
new TreeMap(wordMap).forEach((k, v) ->
System.out.println(String.format("%s word length: 1 ==> %d", k, v)));
return wordMap;
}
}
나는 Ex : File 1, File 2 등의 파일에 번호를 매기 위해 이것을 사용하고있다. –
@Eran 누구나 Array를 발견했기 때문에 이전에 끝났다고 생각했기 때문에! –
@Eran int 카운터가 작동했습니다. 고맙습니다. 그러나 더 이상 질문을 수정할 수있는 옵션이 없습니다. 난 그냥 int를 배치 한 후 [email protected] 물건을 가지고 fileCounter = 0; for 루프에서 fileCounter ++를 사용하고 println 문에서 fileCounter를 연결합니다. –