Question

In: Computer Science

B. Write a program Median.java to read each file whose name is specified in the command-line...

B. Write a program Median.java to read each file whose name is specified in the command-line arguments. That is, for each command-line argument, open it as a file and read it.

The file contents are zero or more lines each containing a list of comma-separated integers, such as 1,2,3,4 or 99,120,33. You should parse each of these integers and save them in an ArrayList (if you prefer you may use an array, but an ArrayList is likely to be easier for this assignment).

Once you have filled your array list with all the integers in the line, you must compute the median value, that is, the integer for which half the integers in the line are above it, and half are below it. There are two subtleties that you should handle correctly:

- each integer may appear more than once: in 1,1,2,2,3, the median is 2

- with an even number of integers, the median may be the average of two of the integers: in 1,2,3,4, the median is 2.5

You must implement and use a method whose header is one of
private static double computeMedian(java.util.ArrayList<Integer> numbers)
or
private static double computeMedian(Integer[] numbers)
or
private static double computeMedian(int[] numbers)

to compute and return the median of all the numbers.

An algorithm to compute the median is as follows:

- for each number in the ArrayList (or array), compare it to all the numbers in the array, computing how many are above it, how many are below it, and how many are the same -- at least one (itself) should be the same.

- then if (the number below plus the number equal are greater than the number above) AND (the number below is less than the number equal plus the number above) then this number is the median.

For example, in 1,1,2,2,3:

- for the number 1, there are 0 numbers below, 2 numbers that are equal, and 3 numbers above, so 1 is not the median.

- for the number 2, there are 2 numbers below, 2 numbers that are equal, and 1 numbers above, so 2 is the median.

- for the number 3, there are 4 numbers below, 1 number that is equal, and 0 numbers above, so 3 is not the median.

On the other hand, if (the number below plus the number equal is the same as the number above) OR (the number below is the same as the number equal plus the number above) then this is one of two numbers, the average of which is the median.

For example, in 1,2,3,4,5,2, for the number 2, there is one number below and two numbers equal, which is the same as the three number above. For the number 3, there is one number equal and two numbers above, which is the same as the three numbers below. So in this case the median is the average of 2 and 3: mathematically, (2 + 3) / 2 = 2.5 (remember the division must be done using doubles, otherwise the result will be truncated).

To correctly implement this part of the computation, you need to have one or more variables declared outside the main loop, to keep track of whether you have already seen one of the two numbers whose average is the mean. In the example above, once you see 3 (after seeing 2), you should be able to immediately return the median 2.5. Be careful -- if you see another 2 (before seeing the 3), as in processing 2,2,1,3,5,4, you must continue your search past the second 2.

Solutions

Expert Solution

Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. 

Let me know for any help with any other questions.

Thank You!

===========================================================================

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class Median {


    private static double computeMedian(ArrayList<Integer> numbers) {

        int mediansFound = 0;
        int firstMedianValue = 0;
        int secondtMedianValue = 0;

        for (Integer num : numbers) {
            int aboveCount = 0;
            int belowCount = 0;

            for (Integer n : numbers) {

                if (num == n) continue;
                if (num > n) aboveCount += 1;
                else if (num < n) belowCount += 1;
            }

            if (aboveCount == belowCount) {

                if (mediansFound == 0) {
                    firstMedianValue = num;
                    mediansFound+=1;
                } else if (mediansFound == 1 && firstMedianValue != num) {
                    secondtMedianValue = num;
                    mediansFound += 1;
                    break;
                }
            }
        }

        if (mediansFound == 1) return firstMedianValue * 1.0;
        else return (firstMedianValue + secondtMedianValue) / 2.0;


    }

    public static void main(String[] args) {


        ArrayList<Integer> numbers = new ArrayList<>();

        for (String file : args) {


            try {
                Scanner fileReader = new Scanner(new File(file));
                while (fileReader.hasNextLine()) {
                    String line = fileReader.nextLine();
                    String[] nums = line.split(",");
                    for (String num : nums) {
                        try {
                            numbers.add(Integer.valueOf(num));
                        } catch (Exception e) {

                        }

                    }
                }
                fileReader.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }


        double median = computeMedian(numbers);

        System.out.println("Median Value: " + median);
    }
}

==================================================================


Related Solutions

Write a program Median.java to read each file whose name is specified in the command-line arguments....
Write a program Median.java to read each file whose name is specified in the command-line arguments. That is, for each command-line argument, open it as a file and read it. The file contents are zero or more lines each containing a list of comma-separated integers, such as 1,2,3,4 or 99,120,33. You should parse each of these integers and save them in an ArrayList (if you prefer you may use an array, but an ArrayList is likely to be easier for...
Write a Java program that allows the user to specify a file name on the command...
Write a Java program that allows the user to specify a file name on the command line and prints the number of characters, words, lines, average number of words per line, and average number of characters per word in that file. If the user does not specify any file name, then prompt the user for the name.
Python program: Write a program that reads a text file named test_scores.txt to read the name...
Python program: Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for 3 tests. The program should display class average for first test (average of scores of test 1) and average (average of 3 tests) for each student. Expected Output: ['John', '25', '26', '27'] ['Michael', '24', '28', '29'] ['Adelle', '23', '24', '20'] [['John', '25', '26', '27'], ['Michael', '24', '28', '29'], ['Adelle', '23', '24', '20']] Class average for test 1...
Write a program that will read in from input file one line at a time until...
Write a program that will read in from input file one line at a time until end of file and output the number of words in the line and the number of occurrences of each letter. Define a word to be any string of letters that is delimited at each end by either whitespace, a period, a comma or the beginning or end of the line. You can assume that the input consists entirely of letters, whitespaces, commas and periods....
Make a modification of the program below, that will read in the string as a “command-line...
Make a modification of the program below, that will read in the string as a “command-line argument” to your program, instead of having the user type it while your program is running. Your program should print out the inverted string to the screen. #include <iostream> #include <cstring> using namespace std; int Reverse(char * destination, const char * source, int num); int main() // this is the test/driver code, for your function { const int STRINGSIZE = 10; char oldCString[] =...
Write a program using python that loops over each file in a specified directory and checks...
Write a program using python that loops over each file in a specified directory and checks the size of each file.You should create 2-tuple with the filename and size, should append the 2-tuple to a list, and then store all the lists in a dictionary.  
(Write/read data) Write a Program in BlueJ to create a file name Excersise12_15.txt if it does...
(Write/read data) Write a Program in BlueJ to create a file name Excersise12_15.txt if it does not exist. Write 100 integers created randomly into the file using text I/O. Integers are separated by spaces in the file. Read data back from the file and display the data in increasing order. After writing the file to disk, the input file should be read into an array, sorted using the static Arrays.sort() method from the Java API and then displayed in the...
Write a program that reads a file line by line, and reads each line’s tokens to...
Write a program that reads a file line by line, and reads each line’s tokens to create a Student object that gets inserted into an ArrayList that holds Student objects.  Each line from the file to read will contain two strings for first and last name, and three floats for three test grades.  After reading the file and filling the ArrayList with Student objects, sort the ArrayList and output the contents of the ArrayList so that the students with the highest average...
Design a program that will read each line of text from a file, print it out...
Design a program that will read each line of text from a file, print it out to the screen in forward and reverse order and determine if it is a palindrome, ignoring case, spaces, and punctuation. (A palindrome is a phrase that reads the same both forwards and backwards.) Example program run: A Toyota's a Toyota atoyoT a s'atoyoT A This is a palindrome! Hello World dlroW olleH This is NOT a palindrome! Note: You are only designing the program...
Write a c++ program that does the following, read temperatures from a file name temp.txt into...
Write a c++ program that does the following, read temperatures from a file name temp.txt into an array, and after reading all the temperatures, output the following information: the average temperature, the minimum temperature, and the total number of temperatures read. Thank you!
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT