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.
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
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++
*C++* /* This program reads a movie rating from 1 to 10 from the user and...
*C++* /* This program reads a movie rating from 1 to 10 from the user and prints a corresponding word for the rating. Programmer: Your name here Date:       Current date here */ #include #include using namespace std; int main() {       int rating; // user entered rating       cout << "Enter your movie rating (an integer from 1 to 10): ";       cin >> rating;       cout << "\nThe movie was ";       // Select the appropriate word for the...
Use DevC++ to implement a program that can store and output 5 integers, where the user...
Use DevC++ to implement a program that can store and output 5 integers, where the user can input its value into an array named arrayValue. The program should implement the following: 1. Calculate the sum and average of the array. 2. Output the content (value) that stored in the array of five elements. 3. Continue to ask the user to store for storing data into another array. c++ ONLY PLEASE NEED IT FAST AS POSSIBLE
Design and implement a C++ program that performs the following steps:Ask the user to enter a...
Design and implement a C++ program that performs the following steps:Ask the user to enter a positive integer number N; Your program may need to prompt the user to enter many times until it reads in a positive number;Let user to enter N (obtained in the previous step) floating point numbers, and count how many positive ones there are in the sequence and sum up these positive numbers; (Hint: negative numbers or 0 are ignored).Display result.You can and should use...
C++ programing Write a main function that  reads a list of integers from a user, adds to...
C++ programing 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.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT