Question

In: Computer Science

Please carefully review the code to fill in after the given instructions and complete the code...

Please carefully review the code to fill in after the given instructions and complete the code for me.

Thank you in advance.

In this problem, we will implement a simple dictionary of common words in the English language, represented as an array of words paired with their lengths. You will need to implement each of the below methods in the Dictionary class. In this problem, the first line of input represents the method to call. It will be one of the following: MIN, MAX, RANGE, AVERAGE, MODE. The second line will represent an integer n, which denotes the number of words in the list. The following n lines will each be a word. The words will not necessarily be sorted. Your output should be a single line representing the results of the method. (a) Implement the minWordLength() method, which should return the length of the smallest word in the list. (b) Implement a method called maxWordLength(), which should return the length of the largest word in the list. (c) Implement a method called wordLengthRange(), which should return the range of lengths in the word list. (d) Implement a method called averageWordLength(), which should return the average word length in the word list. The method should return a string representing the average, accurate to exactly two decimal places (i.e. if the average length is 5, return 5.00). (e) Implement a method called mostCommonWordLength(), which should return the most common length of the words in the list. If there is a tie, you should return -1. You may assume that the length of a word is at most 100 and at least 1.

import java.lang.UnsupportedOperationException;
import java.util.Scanner;

public class Main {
// Constants for function names in input
public static final String MIN_METHOD_NAME = "MIN";
public static final String MAX_METHOD_NAME = "MAX";
public static final String RANGE_METHOD_NAME = "RANGE";
public static final String AVERAGE_METHOD_NAME = "AVERAGE";
public static final String MODE_METHOD_NAME = "MODE";
  
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
  
// Read in the method name that we want to call
String methodName = sc.nextLine();
  
// Read in number of words
int numWords = Integer.parseInt(sc.nextLine());
  
// Read in list of words
String[] words = new String[numWords];
for (int i = 0; i < numWords; i++) {
words[i] = sc.nextLine();
}
  
// Run the specified method
switch (methodName) {
case MIN_METHOD_NAME:
System.out.println(minWordLength(words));
break;
case MAX_METHOD_NAME:
System.out.println(maxWordLength(words));
break;
case RANGE_METHOD_NAME:
System.out.println(wordLengthRange(words));
break;
case AVERAGE_METHOD_NAME:
System.out.println(averageWordLength(words));
break;
case MODE_METHOD_NAME:
System.out.println(mostCommonWordLength(words));
break;
default:
throw new UnsupportedOperationException();   
}
}

private static int minWordLength(String[] words) {
// TODO implement this function
throw new UnsupportedOperationException();
}

private static int maxWordLength(String[] words) {
// TODO implement this function
throw new UnsupportedOperationException();
}

private static int wordLengthRange(String[] words) {
// TODO implement this function
throw new UnsupportedOperationException();
}

private static String averageWordLength(String[] words) {
// TODO implement this function
throw new UnsupportedOperationException();
}

private static int mostCommonWordLength(String[] words) {
// TODO implement this function
throw new UnsupportedOperationException();
}
}

Solutions

Expert Solution

Please find the answer below, all the details are mentioned in the comments.

package september_2019;

import java.lang.UnsupportedOperationException;
import java.util.Scanner;

public class Main {
    // Constants for function names in input
    public static final String MIN_METHOD_NAME = "MIN";
    public static final String MAX_METHOD_NAME = "MAX";
    public static final String RANGE_METHOD_NAME = "RANGE";
    public static final String AVERAGE_METHOD_NAME = "AVERAGE";
    public static final String MODE_METHOD_NAME = "MODE";

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read in the method name that we want to call
        String methodName = sc.nextLine();
        // Read in number of words
        int numWords = Integer.parseInt(sc.nextLine());
        // Read in list of words
        String[] words = new String[numWords];
        for (int i = 0; i < numWords; i++) {
            words[i] = sc.nextLine();
        }

        // Run the specified method
        switch (methodName) {
            case MIN_METHOD_NAME:
                System.out.println(minWordLength(words));
                break;
            case MAX_METHOD_NAME:
                System.out.println(maxWordLength(words));
                break;
            case RANGE_METHOD_NAME:
                System.out.println(wordLengthRange(words));
                break;
            case AVERAGE_METHOD_NAME:
                System.out.println(averageWordLength(words));
                break;
            case MODE_METHOD_NAME:
                System.out.println(mostCommonWordLength(words));
                break;
            default:
                throw new UnsupportedOperationException();
        }
    }

    private static int minWordLength(String[] words) {
        //store answer as the max value
        int ans = Integer.MAX_VALUE;
        
        //find least length form the array
        for (int i =0;i<words.length;i++){
            if(words[i].length() < ans){
                ans = words[i].length();
            }
        }
        return ans;
    }

    private static int maxWordLength(String[] words) {
        //store answer as min value
        int ans = Integer.MIN_VALUE;
        
        //find the max length from the array
        for (int i =0;i<words.length;i++){
            if(words[i].length() > ans){
                ans = words[i].length();
            }
        }
        return ans;
    }

    private static int wordLengthRange(String[] words) {
        //return the range of the max and min length in the array
        return maxWordLength(words) - minWordLength(words);
    }

    private static String averageWordLength(String[] words) {
        double total = 0;
        //get the total of all the values
        for (int i =0;i<words.length;i++){
            total += words[i].length();
        }
        //find the avg of the values
        double average = total / words.length * 1.0;

        //return the 2 decimal string as the answer
        String ans = String.format("%.2f", average);

        return ans;
    }

    private static int mostCommonWordLength(String[] words) {
        int length_counter[] = new int[101];
        int max_length = -1;
        int max = Integer.MIN_VALUE;
        
        //first get the count of all type of length from 1-100
        for (int i =0;i<words.length;i++){
            length_counter[words[i].length()]++;
            //store the max value and max_length value
            if(length_counter[words[i].length()] > max){
                max = length_counter[words[i].length()];
                max_length = words[i].length();
            }
        }

        //search if there is a tie then return -1
        for(int i=0;i<length_counter.length;i++){
            if(length_counter[i] == max){
                if(i != max_length)
                    return -1;
            }
        }
        
        //else return max_length value
        return max_length;
    }
}

Output:

Min:

Max:

Range:

Average:

Mode(1)

Mode(2), tie in common length


Related Solutions

Project Instructions Please read the following instructions and review the table below carefully. Then, enter answers...
Project Instructions Please read the following instructions and review the table below carefully. Then, enter answers for journal items [A] to [V] in the next item in this lesson, called Project 1 Part 1 Journal Entries for Accrual Accounting. You may keep these instructions open in a separate browser or download the instructions as a PDF, and open it as you work through the exercise. Illini Company, Inc. Balance Sheet as of 12/31/20X0 Assets Current Assets: Cash 1,500,000 Accounts receivable,...
Please complete the following code in C using the comments as instructions. Further instructions are below...
Please complete the following code in C using the comments as instructions. Further instructions are below the code. challenge.c // goal: print the environment variables to the file "env.txt", one per line // (If envp is NULL, the file should be empty, opening in write mode will do that.) // example: // inputs: // envp/environ = {"E1=2","E2=7",NULL} // outputs: // env.txt as a string would be "E1=2\nE2=7\n" // example: // inputs: // envp/environ = {NULL} or NULL // outputs: //...
Please read the instructions and  find attached for the first wiki . Instructions for students: Read carefully...
Please read the instructions and  find attached for the first wiki . Instructions for students: Read carefully the attached document and then post your comments bearing in mind the following questions: 1- What are the pros and cons of rent controls? 2- Why economists disagree on the usefulness of rent control? 3- Do you believe rent control can help the poor? Edit Wiki Content rent control Rent regulation can take various forms, including rent control (the placing of a cap on...
c++. please read this task carefully. First, try given examples of input to your code, if...
c++. please read this task carefully. First, try given examples of input to your code, if it works, then send it here. Create structure Applicants with following fields: struct applicants{ int id; string name; string surname; int subject1,subject2,subject3,selectedSubject; string specialCase; int total; }; SpecialCase (if applicant has "Awardee of Olympiads", then this field is "true", otherwise "false"). Do not forget that all "Awardees of Olympiads" will gain grants automatically. If the total points are same your algorithm have to choose...
How would I add an automatic please fill out this info to my complete code. Something...
How would I add an automatic please fill out this info to my complete code. Something similar to this code. <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Untitled Document</title> <script>    function phonenumber(inputtxt){           var phoneno = (\(\d{3}\)|\d{3})[-\s]\d{3}-\d{4};       if(inputtxt.value.match(phoneno)){        document.getElementById("yourEntry").innerHTML = document.getElementById("myphone").value;    }    //if(!inputtxt.value.match(phoneno)){        // alert("Does not Work!")        //}    } </script> </head> <body> <form name="form1" action="#"> <input type="text" name="myphone" id="myphone" value="" pattern= "(\(\d{3}\)|\d{3})[-\s]\d{3}-\d{4}" placeholder="(555) 555-1212" required /> <input...
Please code by Java. The following preemptive program with this problem after sample output(fill random number,...
Please code by Java. The following preemptive program with this problem after sample output(fill random number, recursive search, non-recursive search, exit), You just need to modify this code to add sorting and time calculations. Problem Description: Expand on Lab3 by adding methods that implement Bubble Sort, Selection Sort, Insertion Sort, Merge Sort and Quick Sort for displaying the sorted integers from the randomly generated array. NOTE: Create separate methods for each type of sort. Run Tests for all 4 types...
Given the StudentIDDriver.java file, fill in the ‘gaps’ in the code (designated by insert code here...
Given the StudentIDDriver.java file, fill in the ‘gaps’ in the code (designated by insert code here that “exercises” (tests) the StudentID class by calling its methods. There are six occurrences of ‘insert code here comments’. Above these are comments that help you understand what your code should accomplish.   Don’t forget to comment your StudentIDDriver.java file (including a prologue section at the top of the file). Create a project in Eclipse for your StudentIdDriver. Add another class for it StudentId Sample...
JAVA CODE FILL IN THE BLANKS you are to complete the skeleton program by completing *...
JAVA CODE FILL IN THE BLANKS you are to complete the skeleton program by completing * the To Do sections. I would suggest doing this a * little bit at a time and testing each step before you * go on to the next step. * *           Add whatever code is necessary to complete this assignment *********************************************************************/ //Add whatever code is necessary to complete this assignment public class Methods {    public static void main(String[] args)    {...
Please Read Carefully Before start answering this question. Please follow the instructions. This Question is from...
Please Read Carefully Before start answering this question. Please follow the instructions. This Question is from 'BSBFIM501 Manage budgets and financial plans' course. There are no parts missing for this Question; guaranteed!. This is the original Screenshot direct from the question. Therefore, there are nothing any further information can be provided. Thanks for your understanding and Cooperation. Please answer the following questions from the topics discussed for Prepare, implement, monitor and modify contingency plans: 1.a. Explain the process of preparing...
I need to complete this C++ program. The instructions are in the comments inside the code...
I need to complete this C++ program. The instructions are in the comments inside the code below: ------------------------------------------------------------------------- Original string is: this is a secret! Encypted string is: uijt!jt!b!tfdsfu" Decrypted string is: this is a secret! //Encoding program //Pre-_____? //other necessary stuff here int main() { //create a string to encrypt using a char array cout<< "Original string is: "<<string<<endl; encrypt(string); cout<< "Encrypted string is: "<<string<<endl; decrypt(string); cout<<"Decrypted string is: "<<string<<endl; return 0; } void encrypt(char e[]) { //Write implementation...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT