Question

In: Computer Science

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 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.

Your code must use this algorithm to find the median. There exists a much easier way to find the median, which is to sort the array and look in the middle -- you are not allowed to use sort, and instead you must use the algorithm described here.

In addition to finding the median, your program must correctly handle all exceptions that may be generated as the result of files not existing, files not containing comma-separated lists of integers, or any other exceptions. Your program must catch and correctly handle every exception, print a sensible message in each case, and continue on to the next file.

Although the two problems get equal credit, this second problem is much harder than the first problem, and requires you to practice many of the things we have learned so far in this course.

Solutions

Expert Solution

package com.demo.qa.Dto;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class MedianDemo {
        
        public static void  findMedian(ArrayList a, int n) 
    { 
      
                Collections.sort(a);
                
        if(n % 2 != 0)
        {       
                System.out.println("Median : "+ a.get(n/2));
        }
        
        int n1 = (int) a.get((n-1)/2);
        int n2 = (int) a.get((n)/2);
  
       System.out.println("Median :"+(n1+n2)/2.0);
       
    } 
        
        public static void main(String args[]){  
                
        for(int i=0;i< 1;++i)
        {       
                try  
                {  
                File file=new File("F:/ecllipse projects/demofile.txt"); 
                FileReader fr=new FileReader(file);  
                BufferedReader br=new BufferedReader(fr);   
                StringBuffer sb=new StringBuffer();    
                
                String line;  
                
                
                
                while((line=br.readLine())!=null)  
                { 
                        
                        String str[] = line.split(",");

               ArrayList<Integer> inc = new ArrayList<Integer>();
                        
                for(int j=0;j< str.length;++j)
                {
                        String ss =str[j];              
                        if(ss == null || ss.equals("")==true || ss.contains(" ") == true || ss.contains("\n") == true)
                        {
                                continue;
                        }
                        else
                        {       
                                int q = Integer.parseInt(ss);
                                inc.add(q);
                        }
                        
                }    
                
                System.out.println("List size : " + inc.size());
                
                if(inc.size() != 0)
                {
                        findMedian(inc,inc.size());
                }
                
                
                
                }
                
                
                fr.close();     
                System.out.println("Contents of File: ");  
                
                System.out.println("\n\n\n\n");
                
                
                }  
                catch(Exception e)  
                {  
                  e.printStackTrace(); 
                  System.out.println("Not open");
                }  
            
            
        }
                
                
                }  
}

Related Solutions

Write a program that takes two command line arguments at the time the program is executed....
Write a program that takes two command line arguments at the time the program is executed. You may assume the user enters only decimal numeric characters. The input must be fully qualified, and the user should be notified of any value out of range for a 23-bit unsigned integer. The first argument is to be considered a data field. This data field is to be is operated upon by a mask defined by the second argument. The program should display...
16.15 Lab 5: filter Name this program filter.c. The program takes two command line arguments: the...
16.15 Lab 5: filter Name this program filter.c. The program takes two command line arguments: the name of an input file and the name of an output file. The program should confirm the input and output files can be opened. If a file cannot be opened, print the error message Cannot open file '<filename>' where <filename> is the name of the file and return. fopen() will return 0 if it fails to open a file. Then, the program will read...
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.
Write a program that prints the sum of its command-line arguments (assuming they are numbers). For...
Write a program that prints the sum of its command-line arguments (assuming they are numbers). For example, java Adder 3 2.5 -4.1 should print The sum is 1.4
Write a C++ program that prints out all of the command line arguments passed to the...
Write a C++ program that prints out all of the command line arguments passed to the program. Each command line argument should be separated from the others with a comma and a space. If a command line argument ends in a comma, then another comma should NOT be added
write a program ordered.java Order check Write a program Ordered.java that takes four int command-line arguments...
write a program ordered.java Order check Write a program Ordered.java that takes four int command-line arguments w, x, y, and z. Define a boolean variable whose value is true if the four values are either in strictly ascending order (w < x < y < z) or strictly descending order (w > x > y > z), and false otherwise. Then, display the boolean variable value. NOTE 1: Do not use if statements on this program. NOTE 2: Assume that...
program c Write a program called filesearch that accepts two command-line arguments: A string A filename...
program c Write a program called filesearch that accepts two command-line arguments: A string A filename If the user did not supply both arguments, the program should display an error message and exit. The program opens the given filename. Each line that contains the given string is displayed. Use the strstr function to search each line for the string. You may assume no line is longer than 255 characters. The matching lines are displayed to standard output (normally the screen).
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...
(Intro/Basic) JAVA Write a small program that gets some numbers as command-line arguments and finds the...
(Intro/Basic) JAVA Write a small program that gets some numbers as command-line arguments and finds the maximum of those numbers. You can assume that the user will provide some command-line arguments when running the program (so you don’t have to worry about what to do if the user doesn’t provide any arguments -- that won’t happen). Also, you can assume that all the command line arguments will be floating-point numbers, i.e., numbers with a decimal point, like 2.95.
Complete Question 1a-c 1a) Write a C program that displays all the command line arguments that...
Complete Question 1a-c 1a) Write a C program that displays all the command line arguments that appear on the command line when the program is invoked. Use the file name cl.c for your c program. Test your program with cl hello goodbye and cl 1 2 3 4 5 6 7 8 and cl 1b) Write a C program that reads in a string from the keyboard. Use scanf with the conversion code %s. Recall that the 2nd arg in...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT