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 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...
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...
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...
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...
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...
A young married couple has carefully looked at their budget. After review, they can afford a...
A young married couple has carefully looked at their budget. After review, they can afford a monthly mortgage payment of $1,139.00. They go to their local banker and she offers them a mortgage of 4.08% APR with monthly compounding with a term of 30 years. The couple has enough savings to pay 20% down, so the mortgage will be 80% of the home’s value. What is the mortgage that the couple can apply for based on their budget and the...
Instructions Before beginning work on this assignment, please review the expanded grading rubric for specific instructions...
Instructions Before beginning work on this assignment, please review the expanded grading rubric for specific instructions relating to content and formatting. Risk-Based Reimbursement For your assignment, a primary care physician is often reimbursed by Health Maintenance Organizations (HMOs) via capitation, fee-for-service, relative value scale, or salary. Capitation is considered as a risk based compensation. In an effort to understand the intricacies involved with physician reimbursement, particularly in an era of health care reform, identify and interview an expert in the...
Instructions Before beginning work on this assignment, please review the expanded grading rubric for specific instructions...
Instructions Before beginning work on this assignment, please review the expanded grading rubric for specific instructions relating to content and formatting. See research evaluation checklist below. Using this checklist read and evaluate the article “Diagnosed with Breast Cancer While on a Family History Screening Programme: An Exploratory Qualitative Study.” To support your work, use your course and textbook readings and also use the South University Online Library. As in all assignments, cite your sources in your work and provide references...
Instructions Before beginning work on this assignment, please review the expanded grading rubric for specific instructions...
Instructions Before beginning work on this assignment, please review the expanded grading rubric for specific instructions relating to content and formatting. See the research evaluation checklist below. Using this checklist read and evaluate the article “Diagnosed with Breast Cancer While on a Family History Screening Programme: An Exploratory Qualitative Study.” To support your work, use your course and textbook readings and also use the South University Online Library. As in all assignments, cite your sources in your work and provide...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT