Question

In: Computer Science

1. Design and implement a program that reads a series of integers from the user and...

1. Design and implement a program that reads a series of integers from the user and continually prints their average after every reading. The input stops when the user enters “stop” as the input value. Read each input value as a string, then check if it is “stop” or not. If the string is not “stop”, then, attempt to convert it to an integer using the Integer.parseInt method. If this process throws a NumberFormatException, meaning that the input is not a valid integer, display an appropriate error message and prompt for the number again. Continue reading values until the string “stop” has been entered.

2. Suppose a library is processing an input file containing the titles of books in order to identify duplicates. Write a program that reads all of the titles from an input file called bookTitles.inp and writes them to an output file called duplicateTitles.out. When complete, the output file should contain all titles that are duplicated in the input file. Note that the duplicate titles should be written once, even though the input file may contain same titles multiple times. If there are not duplicate titles in the input file, the output file should be empty. Create the input file using Notepad or another text editor, with one title per line. Make sure you have a number of duplicates, including some with three or more copies.

Solutions

Expert Solution

1. FindAverage.java

import java.util.Scanner;

public class FindAverage {
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        String str;
        int counter = 1;
        int sum = 0;
        int average;
        do{
            System.out.println("Enter a number or to type \"stop\" to end program");
            str = scanner.nextLine();
            try{
                if(!str.equalsIgnoreCase("stop")) {
                    int n = Integer.parseInt(str);
                    sum = sum + n;
                    average = sum / counter;
                    System.out.println("Average is: " + average);
                    counter++;
                }
            } catch (NumberFormatException ex){
                System.out.println("Invalid number, please try again.\n\n");
            }

        } while (!str.equalsIgnoreCase("stop"));
        System.out.println("Good Bye!!!");
    }
}

Output:

2. RemoveDuplicateTitles.java :

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;

public class RemoveDuplicateTitles {
    public static void main(String[] args) throws IOException {
        File inputFile = new File("/Users/a797665/Desktop/inputFile.csv");
        Path outputFile = Files.createTempFile("outputFile", ".csv");

        List<String> inputFileHeaders = CsvParser.getHeadersFromACsv(inputFile);
        Set<String> outputFileHeaders = new HashSet<>(inputFileHeaders);

        List<CsvRows> inputFileRecords = CsvParser.getRecodrsFromACsv(inputFile, inputFileHeaders);

        List<CsvRows> outputFileRecords = removeDuplicateTitles(inputFileRecords);

        CsvParser.writeToCsv(new File(outputFile.toString()), outputFileHeaders, outputFileRecords);

    }

    private static List<CsvRows> removeDuplicateTitles(List<CsvRows> inputFileRecords) {
        inputFileRecords.remove(0);
        Set<String> temp = new HashSet<>();
        for (CsvRows csvRows : inputFileRecords){
            temp.add(csvRows.getKeyVal().get("Title"));
        }
        List<CsvRows> result = new ArrayList<>();
        for (String str : temp){
            CsvRows record = new CsvRows();
            record.put("Title",str);
            result.add(record);
        }
        return result;
    }
}

--------------------------------------------------------CsvRows.java--------------------------------------------

import java.util.LinkedHashMap;
import java.util.Map;

public class CsvRows {
    private Map<String, String> keyVal;
    public CsvRows() {
        keyVal = new LinkedHashMap<>();// you may also use HashMap if you don't need to keep order
    }

    public Map<String, String> getKeyVal() {
        return keyVal;
    }
    public void setKeyVal(Map<String, String> keyVal) {
        this.keyVal = keyVal;
    }
    public void put(String key, String val) {
        keyVal.put(key, val);
    }
    public String get(String key) {
        return keyVal.get(key);
    }
}

--------------------------------------------------------------CsvParser.java-----------------------------------------------

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class CsvParser {
    public static List<CsvRows> getRecodrsFromACsv(File file, List<String> keys) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        List<CsvRows> records = new ArrayList<>();
        boolean isHeader = true;
        String line = null;
        while ((line = br.readLine()) != null) {
            if (isHeader) {// first line is header
                isHeader = false;
                continue;
            }
            CsvRows record = new CsvRows();
            String[] lineSplit = line.split(",");
            for (int i = 0; i < lineSplit.length; i++) {
                record.put(keys.get(i), lineSplit[i]);
            }
            records.add(record);
        }
        br.close();
        return records;
    }
    public static List<String> getHeadersFromACsv(File file) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        List<String> headers = null;
        String line = null;
        while ((line = br.readLine()) != null) {
            String[] lineSplit = line.split(",");
            headers = new ArrayList<>(Arrays.asList(lineSplit));
            break;
        }
        br.close();
        return headers;
    }
    public static void writeToCsv(final File file, final Set<String> headers, final List<CsvRows> records)
            throws IOException {
        FileWriter csvWriter = new FileWriter(file);
        // write headers
        String sep = "";
        String[] headersArr = headers.toArray(new String[headers.size()]);
        for (String header : headersArr) {
            csvWriter.append(sep);
            csvWriter.append(header);
            sep = ",";
        }
        csvWriter.append("\n");
        // write records at each line
        for (CsvRows record : records) {
            sep = "";
            for (int i = 0; i < headersArr.length; i++) {
                csvWriter.append(sep);
                csvWriter.append(record.get(headersArr[i]));
                sep = ",";
            }
            csvWriter.append("\n");
        }
        csvWriter.flush();
        csvWriter.close();
    }
}

Code Screenshot:

Input file:

Output File:

inputFile.csv:

Title
abc
xyz
def
abc
ghi
xyz

Related Solutions

Design and implement a program that reads a series of 10 integers from the user and...
Design and implement a program that reads a series of 10 integers from the user and prints their average. Read each input value as a string, and then attempt to convert it to an integer using the Integer.parseInt method. If this process throws a NumberFormatException (meaning that the input is not a valid number), print an appropriate error message and prompt for the number again. Continue reading values until 10 valid integers have been entered.
Design and implement a program that reads a series of 10 integers from the user and...
Design and implement a program that reads a series of 10 integers from the user and prints their average. Read each input value as a string, then attempt to convert it to an integer using the Integer.parseInt method. If this process throws a NumberFormatException (meaning that the input is not a valid integer), display an appropriate error message and prompt for the number again. Continue reading values until 10 valid integers have been entered.
In C ++, Design and implement a program that reads from the user four integer values...
In C ++, Design and implement a program that reads from the user four integer values between 0 and 100, representing grades. The program then, on separate lines, prints out the entered grades followed by the highest grade, lowest grade, and averages of all four grades. Format the outputs following the sample runs below. Sample run 1: You entered:    95, 80, 100, 70 Highest grade: 100 Lowest grade:   70 Average grade: 86.25
In C++ Design and implement a program (name it ProcessGrades) that reads from the user four...
In C++ Design and implement a program (name it ProcessGrades) that reads from the user four integer values between 0 and 100, representing grades. The program then, on separate lines, prints out the entered grades followed by the highest grade, lowest grade, and averages of all four grades. Format the outputs following the sample runs below.
USING C# Design and implement a program (name it SumValue) that reads three integers (say X,...
USING C# Design and implement a program (name it SumValue) that reads three integers (say X, Y, and Z) and prints out their values on separate lines with proper labels, followed by their average with proper label. Comment your code properly.Format the outputs following the sample runs below. Sample run 1: X = 7 Y = 8 Z = 10 Average = 8.333333333333334
Write two versions of a program that reads from the user a sequence of positive integers...
Write two versions of a program that reads from the user a sequence of positive integers ending with -1, and another positive integer num that the user wishes to search for. The program should then print all the line numbers in sequence entered by the user, that contain num, or a message saying that num does not show at all in the sequence. Your program should interact with the user exactly as it shows in the following example: Please enter...
programing language JAVA: Design and implement an application that reads a sentence from the user, then...
programing language JAVA: Design and implement an application that reads a sentence from the user, then counts all the vowels(a, e, i, o, u) in the entire sentence, and prints the number of vowels in the sentence. vowels may be upercase
1. Write an assembly language program that prompts the user for and reads four integers (x1,...
1. Write an assembly language program that prompts the user for and reads four integers (x1, y1, x2, y2) which represent the coordinates of two points. Make sure you keep track of which number is which. 2. Treat the line between the points as the radius of a sphere and compute the surface area of the sphere. Print the output with a label, such as “The surface area of the sphere is: …”. Hint: The distance between the points is...
Bank Accounts in Java! Design and implement a Java program that does the following: 1) reads...
Bank Accounts in Java! Design and implement a Java program that does the following: 1) reads in the principle 2) reads in additional money deposited each year (treat this as a constant) 3) reads in years to grow, and 4) reads in interest rate And then finally prints out how much money they would have each year. See below for formatting. Enter the principle: XX Enter the annual addition: XX Enter the number of years to grow: XX Enter the...
Write a main function that reads a list of integers from a user, adds to an...
Write a main function that reads a list of integers from a user, adds to an array using dynamic memory allocation, and then displays the array. The program also displays the the largest element in the integer array. Requirement: Using pointer notation. Please do this with C++
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT