Question

In: Computer Science

2. Write a Java program that reads a series of input lines from given file “name.txt”,...

2. Write a Java program that reads a series of input lines from given file “name.txt”, and sorts them into alphabetical order, ignoring the case of words. The program should use the merge sort algorithm so that it efficiently sorts a large file.

Contents of names.text

Slater, KendallLavery, RyanChandler, Arabella "Babe"Chandler, StuartKane, EricaChandler, Adam JrSlater, ZachMontgomery, JacksonChandler, KrystalMartin, JamesMontgomery, BiancaCortlandt, PalmerDevane, AidanMadden, JoshHayward, DavidLavery,k JonathanSmythe, GreenleeCortlandt, OpalMcDermott, AnnieHenry, DiGrey, MariaEnglish, BrookeKeefer, JuliaMartin, JosephMontgomery, LilyDillon, AmandaColby, LizaStone, Mary FrancesChandler, ColbyFrye, DerekMontgomery, ReggieMontgomery, SeanSantos, HayleySantos, MateoDillon, JanetJefferson, KelseyChandler, MarianFargate, MyrtleHenry, DelCodahy, LiviaWarner, AnitaLavery, SpikeMartin, RuthMontgomery, Barbara

Solutions

Expert Solution

ANSWER:

I have provided the properly commented and indented code so you can easily copy the code as well as check for correct indentation.
I have provided the output image of the code so you can easily cross-check for the correct output of the code.
Have a nice and healthy day!!

CODE

import java.util.*;
import java.io.*;

public class Main
{

  public static String [] mergeSort(String [] array){
        String [] list = array;
        
        if(list.length > 1)
        {
            // mid of list
            int mid = list.length / 2;
 
            // Split left part
            String[] left = new String[mid];
            for(int i = 0; i < mid; i++)
            {
                left[i] = list[i];
            }
             
            // Split right part
            String[] right = new String[list.length - mid];
            for(int i = mid; i < list.length; i++)
            {
                right[i - mid] = list[i];
            }
            // calling mergeSort
            mergeSort(left);
            mergeSort(right);
 
            int i = 0;
            int j = 0;
            int k = 0;
 
            // Merge left and right arrays
            while(i < left.length && j < right.length)
            {
                // compare left right string
                // using
                if(left[i].compareTo(right[j]) < 0)
                {
                    list[k] = left[i];
                    i++;
                }
                else
                {
                    list[k] = right[j];
                    j++;
                }
                k++;
            }
            // Collect remaining elements
            while(i < left.length)
            {
                list[k] = left[i];
                i++;
                k++;
            }
            while(j < right.length)
            {
                list[k] = right[j];
                j++;
                k++;
            }
        }
        

        return list;
    }


        public static void main(String[] args) {
            // reading names.txt
                File namesFile = new File("names.txt");
    try
    {
      // creating scanning object on file object
                  Scanner reader = new Scanner(namesFile);
                  // reading file line by line,
                  // creating complete file string object 
                  String data = "";
                  while (reader.hasNextLine()) {
                    // reading line
                    String line = reader.nextLine();
                    // storing line in data, using , seprator
                    data = ","+line;
                  }
                  // display content 
                  // System.out.println(data);
                
                  // spliting string on , using string split method 
                  String[] names = data.split(",");
      // using strip to remove trailing spaces from names
      for(int i=0;i<names.length;i++){
        names[i] = names[i].trim();
        System.out.println(names[i]);
      }
                
                  // merges rot
      String[] sorted = mergeSort(names);
                  System.out.println("");
      // using strip to remove trailing spaces from names
      for(int i=0;i<sorted.length;i++){
        System.out.println(sorted[i]);
      }      
    }
    catch (FileNotFoundException ex)  
    {
        // insert code to run when exception occurs
        System.out.println("FIle not found");
    }
                
            
        }
}

OUTPUT IMAGE

SORTED


Related Solutions

Use C language Write a program that reads in a series of lines of input character...
Use C language Write a program that reads in a series of lines of input character by character (using getchar()). The first line of the input contains an integer which specifies the number of remaining lines of input, each of which contains a floating point number. The integer value on the first line can be read with scanf(), but all of the following lines can only be read with getchar(). Each line after the first contains a single floating point...
Write a C++ or Java program that reads an input graph data from a user. Then,...
Write a C++ or Java program that reads an input graph data from a user. Then, it should present a path for the travelling salesman problem (TSP). In the assignment, you can assume that the maximum number ofvertices in the input graph is less than or equal to 20. Input format: This is a sample input from a user. 4 12 0 1 2 0 3 7 0 2 5 1 0 2 1 2 8 1 3 3 2...
Write a Java program that reads an input graph data from a user. Then, it should...
Write a Java program that reads an input graph data from a user. Then, it should present a path for the travelling salesman problem (TSP). In the assignment, you can assume that the maximum number of vertices in the input graph is less than or equal to 20. Input format: This is a sample input from a user. 4 12 0 1 2 0 3 7 0 2 5 1 0 2 1 2 8 1 3 3 2 0...
Write a JAVA program that reads in a string from standard input and determines the following:...
Write a JAVA program that reads in a string from standard input and determines the following: - How many vowels are in the string (FOR THE PURPOSE OF THIS PROGRAM 'Y' is NOT considered a vowel)? - How many upper case characters are in the string? - How many digits are in the string? - How many white space characters are in the string? - Modify the program to indicate which vowel occurs the most. In the case of a...
Write java program that will ask for the user for 2 input lines and print out...
Write java program that will ask for the user for 2 input lines and print out all words that occur 1 or more times on both lines (case sensitive). Write this without arrays and method. Here is a sample run: <Output> Enter two lines to process. The quick brown fox jumps over a lazy dog The fox hound outruns the lazy dog The words that occur on both lines are: The fox lazy dog
Write a program that reads two strings from an input file (The first line is X,...
Write a program that reads two strings from an input file (The first line is X, the second line is Y), compute the longest common subsequence length AND the resulting string. You will need to write 2 methods 1) return LCS length in iterative function // return the length of LCS. L is the 2D matrix, X, Y are the input strings, m=|X|, n=|Y| int lcs_it(int **C, string X, string Y, int m, int n ) 2) return LCS resulting...
Using Java Project 2: Deduplication Write a program that reads a file of numbers of type...
Using Java Project 2: Deduplication Write a program that reads a file of numbers of type int and outputs all of those numbers to another file, but without any duplicate numbers. You should assume that the input file is sorted from smallest to largest with one number on each line. After the program is run, the output file should contain all numbers that are in the original file, but no number should appear more than once. The numbers in the...
Write a Java program that reads a list of 30 fruits from the file “fruits.txt”, inserts...
Write a Java program that reads a list of 30 fruits from the file “fruits.txt”, inserts them into a string array, and sorts the array in alphabetical order. String objects can be compared using relational operators such as <, >, or ==. For example, “abc” > “abd” is false, but “abc” < “abd” is true. Sample output: Before Sorting: Cherry, Honeydew, Cranberry, Lemon, Orange, Persimmon, Watermelon, Kiwifruit, Lime, Pomegranate, Jujube, Pineapple, Durian, Plum, Banana, Coconut, Apple, Tomato, Raisin, Mandarine, Blackberry,...
JAVA Assignment: Project File Processing. Write a program that will read in from input file one...
JAVA Assignment: Project File Processing. 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...
Java Write a program that will only accept input from a file provided as the first...
Java Write a program that will only accept input from a file provided as the first command line argument. If no file is given or the file cannot be opened, simply print “Error opening file!” and stop executing. A valid input file should contain two lines. The first line is any valid string, and the second line should contain a single integer. The program should then print the single character from the string provided as the first line of input...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT