Skip to content

Instantly share code, notes, and snippets.

@shrey150
Created November 9, 2018 18:57
Show Gist options
  • Select an option

  • Save shrey150/843e298df4aeef00d60391f6f919a839 to your computer and use it in GitHub Desktop.

Select an option

Save shrey150/843e298df4aeef00d60391f6f919a839 to your computer and use it in GitHub Desktop.
GettysburgAddress
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* GettysburgAddress
* @author Shrey Pandya p7
*
*/
public class Main {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> words = new ArrayList<String>();
Scanner in = new Scanner(new File("GettysburgAddress.txt"));
while (in.hasNext())
{
String w = in.next();
// strip commas/periods
w = w.replace(",", "").replace(".", "");
// split at long hyphens
String[] sub = w.split("--");
// push all data
for (String s : sub) words.add(s);
}
in.close();
// ==================================
// Testing
// ==================================
int sum = 0;
String maxWord = "";
// calculate average
for (String s : words) sum += s.length();
double avgLen = (double) sum / words.size();
// find longest word
for (String s : words)
{
if (s.length() > maxWord.length()) maxWord = s;
}
System.out.println("Avg word length: " + avgLen);
System.out.println("Longest word: " + maxWord);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment