如何在文本文件中找到最长和最短的行?

时间:2013-03-06 09:35:31

标签: java

我正在编写一个程序,它使用Scanner方法读取文本文件并输出:单词数,句子数,每个句子的平均单词数,最长的句子和最短的句子。到目前为止,除了最长和最短的句子外,我还有其他一切,我似乎无法弄明白。这是我到目前为止所拥有的......

import java.util.Scanner;
import java.io.*;
import java.io.IOException;
public class TestScanner {
  public static void main(String args[])
  {     Scanner in = new Scanner(System.in);
        String x = in.next();
        double count=0;
        int nbSentences = 0;
        while(in.hasNext())
        {   String word = in.next();
            nbSentences +=getNbSentences(word);
            count++;
        }
        System.out.println("Number of Words: "+ count);
        System.out.println("Number of Sentences: " + nbSentences);
        System.out.println("Average Words In Sentence: " + (count/nbSentences));
        System.out.println("Longest Sentence: ");
        System.out.println("Shortest Sentence: ");
 }
 //**************************number of sentences*********************************
 public static int getNbSentences(String word) 
 {         int result = 0;
       char[] chars = word.toCharArray();
       for(Character c : chars) 
       {    if(c == '.' || c == '!' || c == '?') 
            {   result++; 
            }
       }
       return result;
 }
 //*************************Longest Sentence*************************************


 //This is where I'm stuck....

}

如果有人可以提供帮助,我会非常感激!!

4 个答案:

答案 0 :(得分:1)

Pseodo代码:

  1. 将第一句设为最长和最短。
  2. 对所有句子进行迭代,将它们与最短和最长的句子进行比较。
  3. 如果您发现的句子短于最短,请将其用作最短的句子。
  4. 如果您发现句子长度超过最长,请将其用作最长句子。

答案 1 :(得分:1)

  1. 在您的循环之外初始化int currentSentenceLength = 0int maxSentenceLength = 0
  2. 每个word:增量currentSentenceLength
  3. 如果word包含.!?,请执行:maxSentenceLength = Math.max(currentSentenceLength, maxSentenceLength); currentSentenceLength = 0;
  4. return maxSentenceLength
  5. 你可以用最短的句子做同样的事情。

答案 2 :(得分:0)

根据您的源代码,您需要做的是获取句子中的单词数。然后你可以更新存储句子存储中当前最小/最大字数的变量,或者将句子中单词的数量作为集合,并获得后验的最大值,最小值(最终是平均值)。

明确地:将main方法中的相应行更改为

double count = 0;
int nbSentences = 0;
int nbWordsInASentence = 0;
Collection nbWordsInSentences = new ArrayList<Integer>();
while (in.hasNext())
{   String word = in.next();
    count++;
    nbWordsInASentence++;

    int incrementNbSentences = getNbSentences(word);
    if (incrementNbSentences > 0) {
        nbWordsInASentence.add(nbWordsInASentence);
        nbWordsInASentence = 0;
    }
}

int maxSentenceLength;
int minSentenceLength;
if (nbWordsInSentences.size() > 0)
{   maxSentenceLength = Collections.max(nbWordsInSentences);
    minSentenceLength = Collections.min(nbWordsInSentences);
}
else
{   maxSentenceLength = 0; // use whatever value seems appropriate
    minSentenceLength = 0; // use whatever value seems appropriate
}

但是这只有在getNbSentences的结果永远不会大于1时才有效(输入参数是一个单词会暗示这一点)。

请注意,在暂停标记的情况下,方法getNbSentences的实现可能不正确:该方法在此次事件中返回3.

答案 3 :(得分:0)

以下代码在文本文件中找到最长和最小的行以及行号。(限制:如果两行相同则将第一行视为长行或短行)。 我使用HashMap存储行(行号作为键,行内容作为值)

如果需要添加此代码,请发布。

`包测试;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class LongestAndShortestLineFinder {

static int previousLongLine = 0;
static int previousShortLine = 10000;

public void printLongLine(HashMap longLineMap) {

    Set keyofSet = longLineMap.keySet();
    Iterator itr = keyofSet.iterator();
    while (itr.hasNext()) {
        Integer keys = (Integer) itr.next();
        String value = (String) longLineMap.get(keys);
        System.out.println("Line Number of Longest line: " + keys
                + "\nLongest line: " + value);
    }
}

public void printShortLine(HashMap shortLineMap) {

    Set keyofSet = shortLineMap.keySet();
    Iterator itr = keyofSet.iterator();
    while (itr.hasNext()) {
        Integer keys = (Integer) itr.next();
        String value = (String) shortLineMap.get(keys);

        System.out.println("Line Number of Shortest line: " + keys
                + "\nShortest line: " + value);
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String fileName = "d:\\test.txt";
    // This will reference one line at a time
    String line = null;
    int key = 0;
    int lineSize = 0, lineNumber = 0;

    LongestAndShortestLineFinder ln = new LongestAndShortestLineFinder();

    HashMap longLineMap = new HashMap();
    HashMap shortLineMap = new HashMap();

    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader(fileName);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while ((line = bufferedReader.readLine()) != null) {
            lineNumber++;
            lineSize = line.length();
            if (lineSize > previousLongLine) {
                previousLongLine = lineSize;
                longLineMap.clear();
                longLineMap.put(lineNumber, line);
            }
            if (lineSize < previousShortLine) {
                previousShortLine = lineSize;
                shortLineMap.clear();
                shortLineMap.put(lineNumber, line);
            }

        }
        // Always close files.
        bufferedReader.close();
    } catch (FileNotFoundException ex) {
        System.out.println("Unable to open file '" + fileName + "'");
    } catch (IOException ex) {
        System.out.println("Error reading file '" + fileName + "'");
        // Or we could just do this:
        // ex.printStackTrace();
    }

    ln.printLongLine(longLineMap);
    ln.printShortLine(shortLineMap);
}

 }

`