Question

Using Java, I am trying to read in a file with the format outlined below. "AARON,...

Using Java, I am trying to read in a file with the format outlined below.


"AARON, ELVIA J"   WATER RATE TAKER   WATER MGMNT   "$87,228.00"
"AARON, JEFFERY M"   POLICE OFFICER   POLICE   "$75,372.00"
"AARON, KARINA"   POLICE OFFICER   POLICE   "$75,372.00"
"AARON, KIMBERLEI R"   CHIEF CONTRACT EXPEDITER   GENERAL SERVICES   "$80,916.00"
"ABAD JR, VICENTE M"   CIVIL ENGINEER IV   WATER MGMNT   "$99,648.00"
"ABARCA, ANABEL"   ASST TO THE ALDERMAN   CITY COUNCIL   "$70,764.00"
"ABARCA, EMMANUEL"   GENERAL LABORER - DSS   STREETS & SAN   "$40,560.00"
"ABBATACOLA, ROBERT J"   ELECTRICAL MECHANIC   AVIATION   "$89,440.00"
"ABBATEMARCO, JAMES J"   FIRE ENGINEER   FIRE   "$84,396.00"
"ABBATE, TERRY M"   POLICE OFFICER   POLICE   "$80,724.00"
"ABBOTT, BETTY L"   FOSTER GRANDPARENT   FAMILY & SUPPORT   "$2,756.00"
"ABBOTT, LYNISE M"   CLERK III   POLICE   "$41,784.00"
"ABBRUZZESE, WILLIAM J"   INVESTIGATOR - IPRA II   IPRA   "$65,808.00"
"ABDALLAH, ZAID"   POLICE OFFICER   POLICE   "$65,016.00"
"ABDELHADI, ABDALMAHD"   POLICE OFFICER   POLICE   "$75,372.00"
"ABDELLATIF, AREF R"   FIREFIGHTER (PER ARBITRATORS AWARD)-PARAMEDIC   FIRE   "$90,738.00"
"ABDELMAJEID, AZIZ"   POLICE OFFICER   POLICE   "$75,372.00"
"ABDOLLAHZADEH, ALI"   PARAMEDIC I/C   FIRE   "$81,672.00"
"ABDUL-KARIM, MUHAMMAD A"   ENGINEERING TECHNICIAN VI   WATER MGMNT   "$96,384.00"
"ABDULLAH, ASKIA"   LEGISLATIVE AIDE   CITY COUNCIL   "$25,008.00"

The problem I am having is in splitting the file between arrays. The first array has the name example: AARON, ELVIA J ( with or without the comma makes no difference). The second array hold the department and position example: WATER RATE TAKER   WATER MGMT. The third array holds the salary as a double example: 87228.00. The code I have so far is below,MY ERROR IS OCCURING AT LINE 33 (String tempName = tokenize[1];) . I need to know how to fix the error and what I am doing wrong. The arrays also need to line up so I can match the index places with the correct records example index 0 in each array contains the information for the same person. If I am going about this all wrong please tell me a better way.

import java.io.*;
import java.util.*;
public class PA3 {
    String name;
    String position;
    double salary;

    public PA3(String name, String position, double salary){
        this.name = name;
        this.position = position;
        this.salary = salary;
    } // end constructor

    public static void main(String[] args) throws Exception {
        ArrayList<PA3> employee = new ArrayList<PA3>();
        try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream("empl.txt");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                System.out.println (strLine);
                // split the data by the quotation marks int three separate arrays using string tokenizer
                String[] tokenize = strLine.split(" "); // first split with 4 spaces
                String tempName = tokenize[1]; // name is split and moved to array
                String tempPosition = tokenize[2]; // position is split and moved to array
                String temp = (tokenize[3].replace("$","").replace(",","").replace("\"","")); //replace all unwanted characters
                double tempSalary = Double.parseDouble(temp); // parse string temp to double
                PA3 tempObject = new PA3(tempName, tempPosition, tempSalary); //creates object with data
                employee.add(tempObject);
                } // end while
            in.close();         //Close the input stream
            } // end try
        catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
            } // end catch
    } // end main
}   // end class

0 0
Add a comment Improve this question Transcribed image text
Answer #1

In the provided source code there are below issues identified

1. String split shoud use 3 spaces as per the text file

String[] tokenize = strLine.split(" "); // first split with 3 spaces

2. token should start with zero index instead of 1 index

String tempName = tokenize[0]; // name is split and moved to array

3. For department and position, there should be two token tokenize[1] and token[2]. Then concat both into single element

String tempPosition_1 = tokenize[1]; // department is split
String tempPosition_2 = tokenize[2]; // position is split
String tempPosition = tempPosition_1 + tempPosition_2; // department & position is split and moved to array

So for reference please find below the correct source code for this.

import java.io.*;
import java.util.*;

public class PA3 {
   String name;
   String position;
   double salary;

   public PA3(String name, String position, double salary) {
       this.name = name;
       this.position = position;
       this.salary = salary;
   }

   public static void main(String[] args) throws Exception {
       ArrayList<PA3> employee = new ArrayList<PA3>();
       try {
           // Open the file that is the first command line parameter
           FileInputStream fstream = new FileInputStream("C:\\Krishnendu\\empl.txt");
           // Get the object of DataInputStream
           DataInputStream in = new DataInputStream(fstream);
           BufferedReader br = new BufferedReader(new InputStreamReader(in));
           String strLine;
           // Read File Line By Line
           while ((strLine = br.readLine()) != null) {
               // Print the content on the console
               System.out.println(strLine);
               // split the data by the quotation marks int three separate arrays using string tokenizer
               String[] tokenize = strLine.split(" "); // first split with 3 spaces
               String tempName = tokenize[0]; // name is split and moved to array
               String tempPosition_1 = tokenize[1]; // department is split
               String tempPosition_2 = tokenize[2]; // position is split
               String tempPosition = tempPosition_1 + tempPosition_2; // department & position is split and moved to array
               String temp = (tokenize[3].replace("$", "").replace(",", "").replace("\"", "")); // replace all unwanted characters
               double tempSalary = Double.parseDouble(temp); // parse string temp to double
               PA3 tempObject = new PA3(tempName, tempPosition, tempSalary); // creates object with data
               employee.add(tempObject);
           }
           in.close();
       }
       catch (Exception e) {
           e.printStackTrace();
           System.err.println("Error: " + e.getMessage());
       }
   }

Please let me know if you have further any concern or doubts.

Also find the upload result/outcome screenshot.

Add a comment
Know the answer?
Add Answer to:
Using Java, I am trying to read in a file with the format outlined below. "AARON,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I am trying to read from a file with with text as follows and I am...

    I am trying to read from a file with with text as follows and I am not sure why my code is not working. DHH-2180 110.25 TOB-6851 -258.45 JNO-1438 375.95 CS 145 Computer Science II IPO-5410 834.15 PWV-5792 793.00 Here is a description of what the class must do: AccountFileIO 1. Create a class called AccountFileIO in the uwstout.cs145.labs.lab02 package. (This is a capital i then a capital o for input/output.) a. This class will read data from a file...

  • I have a multithreaded java sorting program that works as follows: 1. A list of double...

    I have a multithreaded java sorting program that works as follows: 1. A list of double values is divided into two smaller lists of equal size 2. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice 3. The two sublists are then merged by a third thread merging thread that merges the two sublists into a single sorted list. SIMPLE EXECUTION >java SortParallel 1000 Sorting is done in 8.172561ms when...

  • Using java fix the code I implemented so that it passes the JUnit Tests. MATRIX3 public...

    Using java fix the code I implemented so that it passes the JUnit Tests. MATRIX3 public class Matrix3 { private double[][] matrix; /** * Creates a 3x3 matrix from an 2D array * @param v array containing 3 components of the desired vector */ public Matrix3(double[][] array) { this.matrix = array; } /** * Clones an existing matrix * @param old an existing Matrix3 object */ public Matrix3(Matrix3 old) { matrix = new double[old.matrix.length][]; for(int i = 0; i <...

  • composed the following java code to read a string from a text file but receiving compiling...

    composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main {   public static void main(String[] args) {     System.out.print("Enter the...

  • I was wondering if I could get some help with a Java Program that I am...

    I was wondering if I could get some help with a Java Program that I am currently working on for homework. When I run the program in Eclipse nothing shows up in the console can you help me out and tell me if I am missing something in my code or what's going on? My Code: public class Payroll { public static void main(String[] args) { } // TODO Auto-generated method stub private int[] employeeId = { 5658845, 4520125, 7895122,...

  • Using Java; Consider the following text file format. Ruminant Shaman 30 Elentriel Shaman 70 Aelkine Druid...

    Using Java; Consider the following text file format. Ruminant Shaman 30 Elentriel Shaman 70 Aelkine Druid 29 Barbatus Druid 70 Ukaimar Mage 47 Mariko Priest 33 Farmbuyer Priest 70 Valefar Warlock 42 Teslar Paladin 64 Nerdsbane Hunter 12 We wish to store information regarding several characters in a video game. Each character has a name, and a class, and a level. This information is repeated, 3 lines per character, for any number of characters. To simplify processing, the very first...

  • This is my current output for my program. I am trying to get the output to...

    This is my current output for my program. I am trying to get the output to look like This is my program Student.java import java.awt.GridLayout; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.swing.JFileChooser; public class Student extends javax.swing.JFrame {     BufferedWriter outWriter;     StudentA s[];     public Student() {         StudentGUI();            }     private void StudentGUI() {         jScrollPane3 = new javax.swing.JScrollPane();         inputFileChooser = new javax.swing.JButton();         outputFileChooser = new javax.swing.JButton();         sortFirtsName = new...

  • Taking this program how can the requirements under it be added in java? import java.util.Scanner; public...

    Taking this program how can the requirements under it be added in java? import java.util.Scanner; public class RetirementSavings {    private static final int MAX_SALARY = 300000;    private static final double MAX_SAVING_RATE = 0.3;    private static final double MAX_INTEREST_RATE = 0.2;    private static final int MAX_YEAR_EMPLOYED = 40;    public static void main(String[] args) {        double savings_rate, interest_rate;        int salary, years_employed;        String name = ""; // name is initialized with an...

  • I am working on the divide/conquer algorithm. I am having a trouble with a print for...

    I am working on the divide/conquer algorithm. I am having a trouble with a print for output from reading the file. Here is my work. When you see I put the comment with TODO. that one I am struck with readfile. I wonder if you'd able to help me to fix the readfile to find a single number. Here is the input3.txt (1 12 13 24 35 46 57 58 69). after that, the output should be 0. int mergeInversion(int...

  • I am currently using eclipse to write in java. A snapshot of the output would be...

    I am currently using eclipse to write in java. A snapshot of the output would be greatly appreciated to verify that the program is indeed working. Thanks in advance for both your time and effort. Here is the previous exercise code: /////////////////////////////////////////////////////Main /******************************************* * Week 5 lab - exercise 1 and exercise 2: * * ArrayList class with search algorithms * ********************************************/ import java.util.*; /** * Class to test sequential search, sorted search, and binary search algorithms * implemented in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT