Question

In: Computer Science

Java. Given an input file with each line representing a record of data and the first...

Java. Given an input file with each line representing a record of data and the first token (word) being the key that the file is sorted on, we want to load it and output the line number and record for any duplicate keys we encounter. Remember we are assuming the file is sorted by the key and we want to output to the screen the records (and line numbers) with duplicate keys. We are given a text file and have to use the scanner class to lod it

Your task is to

  • create a FindDuplicates class with the following:

    • Declaration of an instance variables for the String filename

    • non-default Constructor - creates an object for user passed filename argument

    • Accessor methods return the value of each instance variable

    • Mutator methods that allows th user to set each instance variable (no validation required),

    • a "getDuplicates()" method that reads from the file (until end-of-file) using Scanner class, finds duplicate records based on the first token on each line (the key), and returns as a String the record number and entire duplicate record one to a line (see above Sample output)

      • toString() - returns a String message with the value of the instance variable

Sample Output

Enter File Name: input1.txt

FileName:input1.txt

DUPLICATES

12 102380 CS US W 2.8 3.267 125

14 102395 PPCI US W 2.769 2.5 115

25 102567 PPCI US W 3.192 3.412 112

35 102912 CS US Z 3.81 3.667 88

44 103087 CS US Z 2.956 2.688 90

76 103944 CS US W 3.134 3.294 134

77 103944 CS US W 3.698 3.7 94

86 104046 CS US W 2.863 3.133 65

88 104047 CS US W 3.523 3.524 77

89 104047 CS US O 3.825 3.824 49

91 104048 CS US W 3.071 3 94

92 104048 CS US W 3.114 3.111 44

93 104048 CS US W 3.375 3.6 71

Press any key to continue . . .

Solutions

Expert Solution

Please find the required program along with the comments and output:

NOTE: I'm taking only a sample file that is created with the available records only shown in question, and made duplicated some records.

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

class Main {

    public static void main(String[] args) {

        String fileName = "C:\\Users\\rishi\\IdeaProjects\\Test\\src\\input1.txt";  //input file path

        //creating an object for the FindDuplicates class
        FindDuplicates duplicates = new FindDuplicates(fileName);

        //get the duplicates
        String dups = duplicates.getDuplicates();

        //print the result
        System.out.println("DUPLICATES");
        System.out.println(dups);
    }

}


class FindDuplicates {

    private String filename;

    //non-default Constructor - creates an object for user passed filename argument
    public FindDuplicates(String filename) {
        this.filename = filename;
    }

    //Accessor methods return the value of each instance variable
    public String getFilename() {
        return filename;
    }

    //Mutator methods that allows th user to set each instance variable
    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getDuplicates() {
        String dups = "";   //to store duplicate records
        ArrayList<String> keys = new ArrayList<>();     //to store the non duplicate keys
        try {
            Scanner scanner = new Scanner(new File(filename));  //scanner to read from file
            while (scanner.hasNext()) {     //read until end of file
                String line = scanner.nextLine();   //read the current line
                String[] split = line.split(" ");   //split the current line with space
                String key = split[0].trim();     //get the first word as key
                if(keys.contains(key)) {    //if the key already contains in the list
                    dups = dups + " " + line + "\n";    //if the key is a duplicate, then store the line to return, else continue
                }else {
                    keys.add(key);  //if key is not found in list, then add that key to the list
                }
            }
        }catch (FileNotFoundException fne){
            System.out.println("File not found!");
        }
        return dups;
    }

    @Override
    public String toString() {
        return filename;
    }
}

----------------------------------------

OUTPUT:


Related Solutions

The input file Each line of the input file will contain a sentence with words separated...
The input file Each line of the input file will contain a sentence with words separated by one space. Read a line from the listed below  and use a StringTokenizer to extract the words from the line. The input file . Mary had a little lamb whose fl33ce was white as sn0w And everywhere that @Mary went the 1amb was sure to go. Read the above that contains a paragraph of words. Put all the words in an array, put the...
2. Create a java program that reads a file line by line and extract the first...
2. Create a java program that reads a file line by line and extract the first word.        The program will ask for the name of input and output file. Input file: words.txt today tomorrow sam peterson peter small roy pratt Output file: outwords.txt tomorrow peterson small pratt
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...
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...
IN JAVA Searching and Sorting In An Integer List File IntegerList contains a Java class representing...
IN JAVA Searching and Sorting In An Integer List File IntegerList contains a Java class representing a list of integers. The following public methods are provided: ? IntegerList(int size)—creates a new list of size elements. Elements are initialized to 0. ? void randomize()—fills the list with random integers between 1 and 100, inclusive. ? void print()—prints the array elements and indices ? int search(int target)—looks for value target in the list using a linear (also called sequential) search algorithm. Returns...
In Java please You are given a matrix of characters representing a big box. Each cell...
In Java please You are given a matrix of characters representing a big box. Each cell of the matrix contains one of three characters: " / "which means that the cell is empty; '*', which means that the cell contains an obstacle; '+', which means that the cell contains a small box. You decide to rotate the big box clockwise to see how the small boxes will fall under the gravity. After rotating, each small box falls down until it...
given a input file, parse it and answer the following frequency related questions, using java. -list...
given a input file, parse it and answer the following frequency related questions, using java. -list the most frequent word(s) in the whole file and its frequency. -list sentence(s) with the max. number of occurrences of the word “of” in the entire file and also list the corresponding frequency. program has two arguments; 1st : path to the input text file 2nd : name prefix for the output files ex. $ java assgn1 “./input.txt” “output” outputs: for each question create...
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,...
Assume there is a file called "mydata". each line of the file contains two data items
how do you read in a file in JAVA Assume there is a file called "mydata". each line of the file contains two data items: hours and rate. hours is the represented by the number of hours the worker worked and rate is represented as hourly rate of pay. The first item of data is count indicating how many lines of data are to follow.Methodspay- accepts the number of hours worked and the rate of pay. returns the dollor and cents...
Two data sets are given below, each representing times (in minutes) to complete a given task...
Two data sets are given below, each representing times (in minutes) to complete a given task for two different samples of students. Data Set A: 3.1, 4.7, 7.3, 8.1, 8.1, 8.7, 8.8, 9.1, 9.1, 9.2 Data Set B: 5.2, 5.6, 5.8, 6.9, 7.0, 7.7, 7.9, 8.5, 8.8, 12.5 Complete the back-to-back stem plot for data set B by adding the numbers that belong in each class below, using a class width of 1.  Do not enter spaces between the numbers. If...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT