Question

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 and add it to an AccountList.

2. This class needs no class variables or constructors.

3. Create a method called parseFile that returns an AccountList and takes a file name (String) as a parameter.

CS 145 Computer Science II

This method will read in an input file a line at a time and add any valid account information to an AccountList. The file is formatted so that each line is a separate account. Each line has the format:

<account number> <balance>

The account numbers do not have spaces in them but there is a space between the account number and the balance. See below for an example.

The input files may have errors in them. If a line is incomplete or otherwise corrupted, then it should not be added to the list, but any remaining lines should be processed.

If a line has too much information (i.e. it has values after the balance), any additional information should be ignored.

Create an AccountList that will store the data read in.

Use a Scanner to read from a file with the given file name (the parameter). For each line of input, read in the full line (check the Scanner class to see how to read in an entire line at one time).

With each line, create a new Scanner (use a different variable from the Scanner above) and use that new Scanner to read in the account number and balance. If they are successfully read in, add it to the list.

If the file cannot be opened, then the method should return null.

try-catch blocks will make this easy to do.

Dividing this method into a couple of separate methods may make this easier to do.

4. The AccountFileIO class can be tested by creating a set of files with data expected, calling parseFile and then checking to see if the AccountList returned has the data from the file.

When creating a test file, put it in the project directory and not the package directory. If it is in the project directory, you should be able to do open the file with just the file name.

myFileIO.parseFile("test1.txt");

public Class AccountFileIO{

public AccountList parseFile(String fileName) {

AccountList a=new AccountList();

File file = new File(fileName);

try {

Scanner scanner = new Scanner(file);

int i=0;

while (scanner.hasNext()) {

String[] records = scanner.nextLine().split("\\s+");

scanner.close();

if (records.length >= 2) {

try {

String accountNumber="";

double balance =0.00;

accountNumber=records[0];

a.accts[i].setAccountNum(accountNumber);

balance = Double.parseDouble(records[1]);

a.accts[i].setBalance(balance);

i++;

} catch (NumberFormatException nfe) {

}

}

}

} catch (FileNotFoundException e) {

e.printStackTrace();

return null;

}

return a;

}

public static void main(String[] args) {

AccountFileIO fileIO = new AccountFileIO();

AccountList accounts= fileIO.parseFile("test1.txt");

for (int i = 0; i<accounts.getSize();i++) {

System.out.println(accounts.accts[i]);

}

}

}

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

The reason why it would not read all records is because you have the scanner.close(); inside the while loop. You should NOT be closing it after reading a single line but at the end of the loop after all records are done. I have deleted the line and just made few simple changes like printing errror message instead of stack trace. Since you have not provided me the AccountList class, I could not run the code.
Please check and let me know if the modified code given below works or not. I am here to help. Let me know through comments. If the answer helped, please do rate it. Thank you.

To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class AccountFileIO{

public AccountList parseFile(String fileName) {
AccountList a=new AccountList();
File file = new File(fileName);

try {

Scanner scanner = new Scanner(file);
int i=0;

while (scanner.hasNext()) {
String[] records = scanner.nextLine().split("\\s+");
if (records.length >= 2) {

try {

String accountNumber="";

double balance =0.00;

accountNumber=records[0];

a.accts[i].setAccountNum(accountNumber);

balance = Double.parseDouble(records[1]);

a.accts[i].setBalance(balance);

i++;

} catch (NumberFormatException nfe) {

}

}

}
scanner.close();

} catch (FileNotFoundException e) {

System.out.println(e.getMessage());
return null;

}

return a;

}

public static void main(String[] args) {

AccountFileIO fileIO = new AccountFileIO();

AccountList accounts= fileIO.parseFile("test1.txt");

for (int i = 0; i<accounts.getSize();i++) {

System.out.println(accounts.accts[i]);

}

}

}

Add a comment
Know the answer?
Add Answer to:
I am trying to read from a file with with text as follows and I am...
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
  • Lab 19 - History of Computer Science, A File IO Lab FIRST PART OF CODING LAB:...

    Lab 19 - History of Computer Science, A File IO Lab FIRST PART OF CODING LAB: Step 0 - Getting Starting In this program, we have two classes, FileIO.java and FileReader.java. FileIO.java will be our “driver” program or the main program that will bring the file reading and analysis together. FileReader.java will create the methods we use in FileIO.java to simply read in our file. Main in FileIO For this lab, main() is provided for you in FileIO.java and contains...

  • Java : Please help me correct my code: create a single class (Program11.java) with a main...

    Java : Please help me correct my code: create a single class (Program11.java) with a main method and some auxiliary methods to input a 2-D array from a disk file, input some “transactions” to change the 2-D array and output the changed 2-D array to another file. Your main method will be minimal (see below). Most of the work will go on in your methods. In main, declare (but do not instantiate) 2-D array. Then call the three methods. The...

  • I am told to create a fillArray method that will read integers from the file "data.txt"...

    I am told to create a fillArray method that will read integers from the file "data.txt" and store them in the array. I'm told to assume that the file has no more than 100 items in it. This is what I have so far: public void fillArray() { int curVal;    Scanner input = null; try { input = new Scanner(new File("data.txt")); // set the current number of items in the array to zero while (input.hasNextInt()) { curVal = input.nextInt();...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads...

    import java.util.Scanner; // TASK #1 Add the file I/O import statement here /** This class reads numbers from a file, calculates the mean and standard deviation, and writes the results to a file. */ public class StatsDemo { // TASK #1 Add the throws clause public static void main(String[] args) { double sum = 0; // The sum of the numbers int count = 0; // The number of numbers added double mean = 0; // The average of the...

  • (Java) Rewrite the following exercise below to read inputs from a file and write the output...

    (Java) Rewrite the following exercise below to read inputs from a file and write the output of your program in a text file. Ask the user to enter the input filename. Use try-catch when reading the file. Ask the user to enter a text file name to write the output in it. You may use the try-with-resources syntax. An example to get an idea but you need to have your own design: try ( // Create input files Scanner input...

  • 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...

  • I need help with my computer science 2 lab. First I am asked to run the...

    I need help with my computer science 2 lab. First I am asked to run the following program and check output? public static void main(String []args) { String filename= "output.txt"; File file = new File(fileName);    try{ FileWriter fileWriter = new FileWriter(file, true); fileWriter.write("CS2: we finished the lecuter\n"); fileWriter.close(); }catch (Exception e){ system.out.println("your message"+e); } String inputfileName = "output.text"; File fileToRead = new File (inputfileName); try { Scanner = new Scanner (fileToread); while(Scanner.hasNextLine()){ String line = scanner.nextLine(); system.out.println(line); } }catch(Eception...

  • (JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text...

    (JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text file named pets10.txt with 10 pets (or use the one below). Store this file in the same folder as your “class” file(s). The format is the same format used in the original homework problem. Each line in the file should contain a pet name (String), a comma, a pet’s age (int) in years, another comma, and a pet’s weight (double) in pounds. Perform the...

  • Please provide the full code...the skeleton is down below: Note: Each file must contain an int...

    Please provide the full code...the skeleton is down below: Note: Each file must contain an int at the beginning, stating the number of records in the file. Afterwards, the number of records in the file will follow. Each record that follows will consist of a last name (String), and a gpa (double). However, to test the error handling of your program, the number of records will not always match the int value. All possible combinations should be tested. 1.) Prompt...

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