Question

In: Computer Science

This assignment will give you practice in Handling Exceptions and using File I/O. Language for this...

  • This assignment will give you practice in Handling Exceptions and using File I/O. Language for this program is JAVA

    Part One

  • A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons:
    • The name of the client,
    • the service sold (such as Dinner, Conference, Lodging, and so on),
    • the amount of the sale,
    • and the date of that event.
  • Prompt the user for data to write the file.

    Part Two

  • Write a program that reads the text file as described above, and that writes a separate file for each service category, containing the entries for that category. Name the output files Dinner.txt, Conference.txt, and so on.
  • Enter the name of the output file from Part One as a command line argument.

    Both Parts

  • For all programs, catch and handle the Exceptions appropriately and validate the input data where needed.
  • Display an error if the sales file does not exist or the format is incorrect.
  • Also, create your own exception to handle "unknown transaction" exceptions.

    Samples:

    • Contents of sales.txt (file created in part one)
      John Public;Dinner;29.95;6/7/2014
      Jane Public;Conference;499.00;8/9/2014
      Abby Lawrence;Dinner;23.45;10/10/2014
      
    • Contents of Dinner.txt (file created in part two)
      John Public;Dinner;29.95;6/7/2014
      Abby Lawrence;Dinner;23.45;10/10/2014
      
    • Contents of Conference.txt (file created in part two)
      Jane Public;Conference;499.0;8/9/2014

Solutions

Expert Solution

The program to write data to Sample.txt is SalesInfo.java and for the part 2 its HotelRecords.java

  1. Also, there is a class named UnknownTransaction.java that is custom exception , whenever the format of the file is not correct this exception is thrown.
  2. Please make sure you go through comments once before running the program, it is very important specially while doing inputs.
  3. Wherever filename or path is asked please enter in the format: C:\\Users\\<Username>\\Desktop, if you want to create file in desktop, otherwise make inputs accordingly.(Also specified in the comment)

Part one:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class SalesInfo {
    public static void main(String[] args) throws Exception {
        File file=null;
        // Enter the name of the file from which data has to be parsed , example : Sample.txt
        /*If the file is C:\Users\<name>\Desktop\Sample.txt
         *  then Enter the filename as C:\\Users\\<name>\\Desktop\\Sample.txt
         * Because java takes '\' as escape sequence hence '\\' is used . Please enter the filename properly
         */
        BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the filename from which data has to be parsed");
        String filename=in.readLine();
        try {
            file = new File(filename);
            if(!file.exists())
                file.createNewFile();
            while(true){
                    System.out.println("Enter the name of Client: ");
                    String client=in.readLine();
                    System.out.println("Enter the Service category sold: ");
                    String Category=in.readLine();
                    System.out.println("Enter the amount of the sale: ");
                    String amount=in.readLine();
                    System.out.println("Please enter the date in the correct format(dd/MM/yyyy)");
                    String date=in.readLine();
                    String value= client+";"+Category+";"+amount+";"+date;
                    System.out.println(value);
                    FileWriter fr = new FileWriter(file, true);
                    BufferedWriter bw = new BufferedWriter(fr);
                    bw.write("\n"+value);
                    
                    bw.close();
                    System.out.println("Do you want to input more data(Y/N) ?");
                    String s=in.readLine();
                    System.out.println(s);
                    if(s.equals("N"))
                        break;
            }
            
           
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
//        finally {
//            br.close();
//        }
    }
}

Part 2:

import java.io.*;
public class HotelRecords {
    public static void main(String[] args) throws Exception {
        File file=null;
        BufferedReader br=null;
        
        // Enter the name of the file from which data has to be parsed , example : Sample.txt
        /*If the file is C:\Users\<name>\Desktop\Sample.txt
         *  then Enter the filename as C:\\Users\\<name>\\Desktop\\Sample.txt
         * Because java takes '\' as escape sequence hence '\\' is used . Please enter the filename properly
         */
        BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the filename from which data has to be parsed");
        String filename=in.readLine();
        
        try {
            file = new File(filename);
            
            //if there is no such file , it throws file not found exception
            br = new BufferedReader(new FileReader(file));

            String st;
            while ((st = br.readLine()) != null) {
                String input[] = st.split(";");
                
                //Please enter the path as described above with '\\' in place of '\'
                System.out.println("Enter the path where you want to create the files");
                String path=in.readLine();
                
                //The data separated by ; has to be 4 according to question, if not throws UnknownTrnsaction
                if(input.length==4){
                        File f1 = new File(path +"\\"+ input[1] + ".txt");
                        // If the file does not exists
                        if (!f1.exists())
                            f1.createNewFile();
                        FileWriter fr = new FileWriter(f1, true);
                        BufferedWriter bw = new BufferedWriter(fr);
                        bw.write(st+"\n");
                        bw.close();
                }
                else{
                        throw new UnknownTransaction("The format for the transaction is not known");
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch(UnknownTransaction e){
                System.out.println(e.getMessage());
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        finally {
                
            br.close();
        }
    }
}

Custom Exception:

class UnknownTransaction extends Exception 
{ 
    public UnknownTransaction(String s) 
    { 
        // Call constructor of parent Exception 
        super(s); 
    } 
}

Related Solutions

in c++ language This assignment is to give you practice using structs and sorting. In competitive...
in c++ language This assignment is to give you practice using structs and sorting. In competitive diving, each diver makes dives of varying degrees of difficulty. Nine judges score each dive from 0 through 10 in steps of 0.5. The difficulty is a floating-point value between 1.0 and 3.0 that represents how complex the dive is to perform. The total score is obtained by discarding the lowest and highest of the judges’ scores, adding the remaining scores, and then multiplying...
Learning objectives; File I/O practice, exceptions, binary search, recursion. Design and implement a recursive version of...
Learning objectives; File I/O practice, exceptions, binary search, recursion. Design and implement a recursive version of a binary search. Instead of using a loop to repeatedly check for the target value, use calls to a recursive method to check one value at a time. If the value is not the target, refine the search space and call the method again. The name to search for is entered by the user, as is the indexes that define the range of viable...
JAVA CODE Learning objectives; File I/O practice, exceptions, binary search, recursion. Design and implement a recursive...
JAVA CODE Learning objectives; File I/O practice, exceptions, binary search, recursion. Design and implement a recursive version of a binary search.  Instead of using a loop to repeatedly check for the target value, use calls to a recursive method to check one value at a time.  If the value is not the target, refine the search space and call the method again.  The name to search for is entered by the user, as is the indexes that define the range of viable candidates...
05 Prepare : Checkpoint A Objective This assignment will give you practice writing event handling methods...
05 Prepare : Checkpoint A Objective This assignment will give you practice writing event handling methods to advance a ship in two dimensional space. Overview After completing (or while completing) the preparation material for this week, complete the following exercise. For this exercise, you will create a class that models a ship flying around in a 2-D plain (containing an x and y coordinate). A game class is provided to you that will help you call methods to advance and...
5) File I/O A) Compare and contrast InputStream/OutputStream based file I/O to Scanner/Printwriter based file I/O:...
5) File I/O A) Compare and contrast InputStream/OutputStream based file I/O to Scanner/Printwriter based file I/O: B) Discuss Serialization, what is it? What are the processes and features? What is the function of the keyword Transient?
This assignment is to give you practice using struts, arrays, and sorting. (Objective C++ and please...
This assignment is to give you practice using struts, arrays, and sorting. (Objective C++ and please have a screenshot of output) In competitive diving, each diver makes dives of varying degrees of difficulty. Nine judges score each dive from 0 through 10 in steps of 0.5. The difficulty is a floating-point value between 1.0 and 3.0 that represents how complex the dive is to perform. The total score is obtained by discarding the lowest and highest of the judges’ scores,...
This assignment is to give you practice using enums, string variables, and string functions. In order...
This assignment is to give you practice using enums, string variables, and string functions. In order to get full credit for the program you must use these three topics. You are to write a program that will read a series of names of people from a data file that has been created with extra blank spaces and reformat the names into a standardized format. The datafile is mp6names.txt. It is arranged with the information for one person on each line....
Java Programming Project 6: File I/O Purpose: To practice reading from as well as writing to...
Java Programming Project 6: File I/O Purpose: To practice reading from as well as writing to text files with the help of Scanner class methods, and PrintStream class methods. You will also learn to implement some simple Exception Handling. Carefully examine and follow ALL the program specifications. Take a look at the PPT slides for Chapter 7 File I/O for examples that will help with this program. Hotel Expense Recording Keeping: A hotel bookkeeper enters client hotel expenses in a...
demonstrate how to write a file named "hcsi 112.txt" while handling exceptions, the sentence given below...
demonstrate how to write a file named "hcsi 112.txt" while handling exceptions, the sentence given below into separate lines(i.e. each sentence begins from where the comma starts) "how are you today?, my name is Python, am easy to use, simple to write, and object oriented". Also show how to read the lines and store into a list.
This assignment covers file I/O. Must design and code a program that can accomplish four things:...
This assignment covers file I/O. Must design and code a program that can accomplish four things: copy one file to another (i.e., place the contents of file A into file B), ‘compress’ a file by removing all vowels (a, e, i, o, u, and y) from the file, merge two files, and finally double each line of an input file, saving into an output file. Also make it so the input file's content can be changed from the example given....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT