user2139177
user2139177

Reputation: 1

How can I find the longest and shortest line in a text file?

I am writing a program that uses the Scanner method to read a text file and outputs: the number of words, Number of sentences, Average number of words per sentence, The longest sentence and shortest sentence. So far I have everything but the longest and shortest sentences and I can't seem to figure them out. Here's what I have so far...

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....

}

If anyone could help I would HIGHLY appreciate it!!

Upvotes: 0

Views: 6956

Answers (4)

Rachangouda Patil
Rachangouda Patil

Reputation: 171

The below code finds the longest and smallest line along with line number from text file.(Limitation: if two lines are same then it considers first one as long or short line). I have used HashMap for storing line(line number as key and line content as value)

If anything need to be add to this code please post.

` package test;

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);
}

 }

`

Upvotes: 1

cooltea
cooltea

Reputation: 1113

According to your source code, what you would need to do is to obtain the number of words in a sentence. Then you can either update variables which would store the current min/max number of words in a sentence store or sotre the number of words in sentences as a collection and obtain the max, min (and eventually the average) a posteriori.

Explicitly: change the corresponding lines in the main method to

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
}

But this only works if the result from getNbSentences is never larger than 1 (which would be implied by the fact that the input argument is a word).

Please note that the implementation of the method getNbSentences the hypothesis might not be true in the case of suspension marks: the method returns 3 in this occurrence.

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53829

  1. Initialize int currentSentenceLength = 0 and int maxSentenceLength = 0 outside of your loop.
  2. For each word: increment currentSentenceLength.
  3. If word contains ., ! or ? do : maxSentenceLength = Math.max(currentSentenceLength, maxSentenceLength); currentSentenceLength = 0;
  4. return maxSentenceLength

You can do the same thing for the shortest sentence.

Upvotes: 1

BobTheBuilder
BobTheBuilder

Reputation: 19284

Pseodo code:

  1. Set first sentence as longest and shortest.
  2. Iterate over all sentences, compare them to the shortest and longest.
  3. If you find a shorter sentence than shortest, use it as shortest.
  4. If you find a longer sentence than longest, use it as longest.

Upvotes: 1

Related Questions