Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.nio.charset.StandardCharsets;
- import java.nio.file.NoSuchFileException;
- import java.util.Scanner;
- import java.util.ArrayList;
- import java.util.LinkedHashMap;
- import java.util.Map;
- public class WordStatInput {
- private static boolean isLegalCharacter(char c) {
- return ((Character.isLetter(c)) || (Character.getType(c) == Character.DASH_PUNCTUATION) || (c == '\''));
- }
- public static void main(String[] args) {
- Map<String, Integer> wordsStats = new LinkedHashMap<String, Integer>();
- // :NOTE: why do you allocate extra memory for input output files?
- String inputFile = args[0];
- String outputFile = args[1];
- try (BufferedReader reader = new BufferedReader(new FileReader(inputFile, StandardCharsets.UTF_8))) {
- // :NOTE: use StringBuilder
- String line;
- // :NOTE: if the input is given a very large string, readLine() will break
- while ((line = reader.readLine()) != null) {
- int startIndex = 0;
- // :NOTE: crutch
- line += " ";
- for (int index = 0; index < line.length(); index++) {
- char character = line.charAt(index);
- if (!isLegalCharacter(character)) {
- // :NOTE: same
- String word = line.substring(startIndex, index).toLowerCase();
- if (!word.isEmpty()) {
- // :NOTE: use getOrDefault method instead of if else
- if (!wordsStats.containsKey(word)) {
- wordsStats.put(word, 1);
- } else {
- // :NOTE: extra memory
- Integer wordOccurence = (Integer) wordsStats.get(word);
- wordsStats.put(word, wordOccurence + 1);
- }
- }
- startIndex = index + 1;
- }
- }
- }
- } catch (FileNotFoundException e) {
- // :NOTE: user wants to read the detailed message of the throwable exception (use getMessage)
- System.out.println("Unable to access file");
- } catch (IllegalArgumentException e) {
- // :NOTE: same
- System.out.println("Passed an unsuitable argument");
- } catch (IOException e) {
- // :NOTE: same
- System.out.println("Unable to read file");
- }
- try (BufferedWriter out = new BufferedWriter(new FileWriter(outputFile, StandardCharsets.UTF_8))) {
- for (Map.Entry<String, Integer> entry : wordsStats.entrySet()) {
- out.write(entry.getKey() + " " + entry.getValue() + System.lineSeparator().toString());
- }
- // :NOTE: you can use general try to catch same exceptions
- } catch (IllegalArgumentException e) {
- // :NOTE: same
- System.out.println("Passed an unsuitable argument");
- // :NOTE: why do you use NoSuchFile? maybe it is better to use FileNotFound?
- } catch (NoSuchFileException e) {
- // :NOTE: same
- System.out.println("File does not exist");
- } catch (IOException e) {
- // :NOTE: same
- System.out.println("Unable to write file");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement