In: Computer Science
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.
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