Created
November 23, 2012 17:12
-
-
Save lounestor/4136513 to your computer and use it in GitHub Desktop.
Count the words in a sentence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static List wordCount(String fileName) { | |
| List list = new ArrayList(); | |
| String input = fileName; | |
| int words = 0; | |
| int totalchar = 0; | |
| int lines = 0; | |
| int longestWord = 0; | |
| int shortestWord = 99999; | |
| try{ | |
| //System.out.println("Reading from file: " + input); | |
| Scanner scan = new Scanner (new File(input)); | |
| while(scan.hasNext()){ | |
| String word = scan.next(); | |
| for(int i = 0;i<word.length();i++){ | |
| totalchar++; | |
| } | |
| if(word.length() > longestWord){ | |
| longestWord = word.length(); | |
| } | |
| if(word.length() < shortestWord){ | |
| shortestWord = word.length(); | |
| } | |
| words++; | |
| } | |
| scan.close(); | |
| scan = new Scanner (new File(input)); | |
| while(scan.hasNextLine()){ | |
| String line = scan.nextLine(); | |
| lines++; | |
| } | |
| int printLongestWord = longestWord; | |
| int printShortestWord = shortestWord; | |
| int avg = totalchar/words; | |
| String avrg = Integer.toString(avg); | |
| //average = number words / total letters | |
| double average = Double.parseDouble(avrg); | |
| System.out.println(words+" "+lines); | |
| list.add(words + " words"); | |
| list.add(lines+ " lines in total"); | |
| list.add(printLongestWord + " longest word"); | |
| list.add(printShortestWord + " smallest word"); | |
| list.add(totalchar+ " char"); | |
| list.add(average + " average word size"); | |
| scan.close(); | |
| }catch(IOException E){ | |
| }return list; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment