Write a method called wordLengths that accepts a Scanner for an input file as it
ID: 3533064 • Letter: W
Question
Write a method called wordLengths that accepts a Scanner for an input file as its parameters. Your method should open the given file, count the number of letters in each taken in the file, and output a result diagram of how many words contain each number of letters. For example, consider a file containing the follwing text:
Before sorting:
13 23 480 -18 75
hello how are you feeling today
After sorting:
-18 13 23 75 480
are you feeling hello today you
Your method should produce the following output to the console. Use tabs so that the stars line up:
1: 0
2: 6 ******
3: 10 **********
4: 0
5: 5 *****
6: 1 *
7: 2 **
8: 2**
Assume that no token in the file is more than 80 characters in length.
Explanation / Answer
package fileexamples; import java.io.File; import java.util.Scanner; public class MostCommon { public static void main(String[] args) throws Exception { Scanner input; int x; // Used to store numbers as we read them. int smallest; // The smallest number in the file int largest; // The largest number in that file int mostCommon; // The number that appears the most times int maxCount; // How many times it appears // Find the smallest number in the file input = new Scanner(new File("numbers.txt")); x = input.nextInt(); smallest = x; while (input.hasNextInt()) { x = input.nextInt(); if (x largest) { largest = x; } } input.close(); // For each number in the range from smallest to largest mostCommon = smallest; maxCount = 1; int n = smallest; while (n maxCount) { maxCount = count; mostCommon = n; } n++; } // Print the results System.out.println("The most common number is " + mostCommon); System.out.println("It appears " + maxCount + " times in the file."); } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.