Подсчитайте количество слов, если «read» не прочитает файл - PullRequest
0 голосов
/ 27 октября 2018

Я делаю программу, которая делает несколько вещей. Сначала он запрашивает у пользователя имя файла через консоль. Затем пользователю предлагается сделать выбор из трех разных команд: чтение, контент или остановка. Мой вопрос о прочитанной части. Он должен показать количество слов в данном файле. Файл читается в отдельном классе openTextFile (). Итак, я должен связать регистр "read" в основной строке с openTextFile () и отобразить общее количество слов.

В этот момент я застрял. Просто не знаю, как пройти через входящий поток и посчитать количество слов. Может кто-нибудь помочь мне здесь?

package nl.ru.ai.SjoerdSam.exercise7;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Concordances
{

  final static int MAX_NR_OF_WORDS=20000;
  public static void main(String[] args) throws FileNotFoundException
  {
    try
    {
      String[] words=new String[MAX_NR_OF_WORDS];
      int[] freqs=new int[MAX_NR_OF_WORDS];
      boolean terminate=true;
      Scanner scanner=openTextFile();
      int nr=findAndCountWords(scanner,words,freqs);
      while(terminate)
      {
        Scanner input=new Scanner(System.in);
        System.out.println("Please enter 'read' to start reading a file and display number of words read, "+"'content' to display content (all currently stored words in the order of apperance), "+"'stop' to stop the program or "+"'count'+ the word you want to count to count the number of occurences of a word, "+"the total number of words and the percantage of occurences.");
        String command=input.nextLine();

        switch(command)
        {
          case "read":
            System.out.println("The number of words in this file is"+nr);
            break;
          case "content":
            displayWords(nr,words,freqs);
            break;
          case "stop":
            terminate=false;
            System.out.println("Program terminated");
            break;
          case "count":
            // Under construction: Bit stuck here on how to do the count and show the frequency of a single word. if i would actually get the frequency the percentage could be found by dividing the frequency with total number of words found above
            Scanner single=new Scanner(System.in);
            System.out.println("Please type in the word you want to know data of");
            String word=single.nextLine();
            findAndCountWord(scanner,words,word);
            System.out.println("The frequency for the word"+" "+single+" "+"is"+findAndCountWord(single,words,word));
            break;

        }
      }
    }
    catch(IllegalArgumentException e)
    {
      System.out.print(e);
    }
  }
  static Scanner openTextFile() throws FileNotFoundException
  {
    assert (true);
    Scanner input=new Scanner(System.in);
    System.out.println("Please enter file name: ");
    String fileName=input.nextLine();
    FileInputStream inputStream=new FileInputStream(fileName);
    return new Scanner(inputStream);
  }
  static int findAndCountWords(Scanner scanner, String[] words, int[] freqs)
  {
    assert words!=null&&freqs!=null;
    int nr=0;
    while(scanner.hasNext())
    {
      String word=scanner.next();
      if(updateWord(word,words,freqs,nr))
        nr++;
    }
    return nr;
  }
  static boolean updateWord(String word, String[] words, int[] freqs, int nr)
  {
    assert nr>=0&&words!=null&&freqs!=null;
    int pos=sequentialSearch(words,0,nr,word);
    if(pos<nr)
    {
      freqs[pos]++;
      return false;
    } else
    {
      words[pos]=word;
      freqs[pos]=1;
      return true;
    }
  }
  static int sequentialSearch(String[] array, int from, int to, String searchValue)
  {
    assert 0<=from&&0<=to : "Invalidbounds";
    assert array!=null : "Array shouldbeinitialized";
    if(from>to)
      return to;
    int position=from;
    while(position<to&&(!array[position].equals(searchValue)))
      position++;
    return position;
  }
  static void displayFrequencies(int nr, String[] words, int[] freqs)
  {
    assert nr>=0&&words!=null&&freqs!=null;

    for(int i=0;i<nr;i++)
    {
      System.out.println(words[i]+" "+freqs[i]);
    }
  }
  static void displayWords(int nr, String[] words, int[] freqs)
  {
    assert nr>=0&&words!=null&&freqs!=null;

    for(int i=0;i<nr;i++)
    {
      System.out.println(words[i]);
    }
  }

  static int findAndCountWord(Scanner scanner, String[] words, String word)
  {
    assert words!=null;
    int wordCount=0;
    while(scanner.hasNext())
    {
      for(int i=0;i<words.length;i++)
      {
        if(word.equals(words[i]))
        {
          wordCount++;
        }
      }
    }
    return wordCount;
  }
}

1 Ответ

0 голосов
/ 27 октября 2018

Отредактировано согласно комментарию ниже:

import java.io.File;
import java.util.Scanner;
public class Count {
public static int countWords(Scanner sc){
int wordsCount=0;

while(sc.hasNext()){
   sc.next();
   wordsCount++;
 }
  System.out.println("wordsCount: " + wordsCount);
  return wordsCount;
}
public static void main(String[] args) throws Exception {
    Scanner scanner = new Scanner(new File("/Users/shiva/Desktop/file.txt"));
    countWords(scanner);
}
}
...