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

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,...
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.
Purpose This assignment should give you experience in using file descriptors, open(), close(), write(), stat() and...
Purpose This assignment should give you experience in using file descriptors, open(), close(), write(), stat() and chmod(), perror(), and command line arguments. Program Write a C++ program that will allow you to add messages to a file that has NO permissions for any user. A Unix system has many files that have sensitive information in them. Permissions help keep these files secure. Some files can be publicly read, but can not be altered by a regular user (ex.: /etc/passwd). Other...
Programming Assignment #3: SimpleFigure and CirclesProgram Description:This assignment will give you practice with value...
Programming Assignment #3: SimpleFigure and CirclesProgram Description:This assignment will give you practice with value parameters, using Java objects, and graphics. This assignment has 2 parts; therefore you should turn in two Java files.You will be using a special class called DrawingPanel written by the instructor, and classes called Graphics and Color that are part of the Java class libraries.Part 1 of 2 (4 points)Simple Figure, or your own drawingFor the first part of this assignment, turn in a file named...
Assignment Overview IN C++ This assignment will give you practice with numerical calculations, simple input/output, and...
Assignment Overview IN C++ This assignment will give you practice with numerical calculations, simple input/output, and if-else statements. Candy Calculator [50 points] The Harris-Benedict equation estimates the number of calories your body needs to maintain your weight if you do no exercise. This is called your basal metabolic rate or BMR. The calories needed for a woman to maintain her weight is: BMR = 655 + (4.3 * weight in pounds) + (4.7 * height in inches) - (4.7 *...
Assignment Overview This assignment will give you practice with interactive programs and if/else statements. Part 1:...
Assignment Overview This assignment will give you practice with interactive programs and if/else statements. Part 1: User name Generator Write a program that prompts for and reads the user’s first and last name (separately). Then print a string composed of the first letter of the user’s first name, followed by the first five characters of the user’s last name, followed by a random number in the range 10 to 99. Assume that the last name is at least five letters...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT