简体   繁体   中英

Need help reading lines from a text file and adding them to an ArrayList

For my homework assignment, I'm supposed to create an ATM/Teller program which stores users accounts in a text file. I require help reading the text file and storing certain parts of it in an array list.

import java.io.*;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.BufferedReader;

public class GetData
{
  public static void main(String[] args)
  {
    BufferedReader in = new BufferedReader(new FileReader("filefullofmoney.txt"));

    String strLine;
    int numberOfLines = 0;    
    while ((strLine = in.readLine()) != null)
    {
      numberOfLines++;
    }

    Database[] accounts = new Database[numberOfLines];
    String[] array1 = new String[3];

    int i;
    int j = 0;

    while (j < numberOfLines)
    {
      for (i=0; i < 2; i++)
      {
        array1[i] = in.readLine();     
      }
      accounts.add(new Database(array[0],array[1],array[2]));
    }
  }
}

class Database
{
  public String accountName;
  public int pin;
  public double balance;
}

The part I'm having trouble with is accounts.add(new Database(array[0],array[1],array[2]));

Basically my text file will be formatted in this way:

Account1 name
Account1 pin
Account1 balance
Account2 name
Account2 pin
Account2 balance
etc...

I want to be able to add the 3 lines of text for each account into one element on the arraylist.

I'm not sure how much of my could actually works because I can't get it to compile.

Any help is greatly appreciated. Thanks

A few problems with your code are:

  • You do not have a specified constructor for your Database class (which should be named Account ).
  • You do not substring the lines, so you get along all the "Database#" prefixes.
    • And may I ask why you even have the prefixes there? They seem superfluous.
  • You do not cast the string s to the actual data types ( int and double ).
  • You loop over the content twice when you only need to do so once.
  • You do not have proper exception handling; you should never wrap everything in one catch(Exception) .

A possible solution to your code could be this (I have not tested if it actually works):

private static String getLineContent(String value) {
    return value.substring(value.indexOf(' ') + 1);
}

public static void main(String[] args) {
    BufferedReader in;
    try {
        in = new BufferedReader(new FileReader("filefullofmoney.txt"));
    } catch (FileNotFoundException ex) {
        // TODO: Handle the error with a nice error message.
        return;
    }

    List<Account> accounts = new ArrayList<Account>();

    while (true) {
        try {
            String accountName = in.readLine();

            if (accountName == null) {
                // We have no new accounts. So we exit.
                break;
            }

            accountName = getLineContent(accountName);
            int pin = Integer.parseInt(getLineContent(in.readLine()));
            double balance = Double.parseDouble(getLineContent(in.readLine()));

            accounts.add(new Account(accountName, pin, balance));
        } catch (IOException ex) {
            // TODO: Handle the error with a nice message saying that the file is malformed.
        }
    }
}

class Account {

    public String accountName;
    public int pin;
    public double balance;

    public Account(String accountName, int pin, double balance) {
        this.accountName = accountName;
        this.pin = pin;
        this.balance = balance;
    }
}

You are using array1 and array choose one and it will compile.

Also you should combine those two while loops. Hint: you don't need to know the numberOfLines .

Rename the class to Account instead of Database .

Then: the readLine() method will return the whole line, so:

Account1 Martijn Courteaux

will be one line. To take the name from it, you can use String.substring() :

String line = null; // Temp
String name = (line = in.readLine()).substring(line.indexOf(' '));

Do the same for the two other values:

int pin = Integer.parseInt((line = in.readLine()).substring(line.indexOf(' ')));
double balance = Double.parseDouble((line = in.readLine()).substring(line.indexOf(' ')));

Then use the values to pass them to the constructor:

accounts.add(new Account(name, pin, balance));

You should probably change

Database[] accounts = new Database[numberOfLines];

to be

ArrayList<String[]> accounts = new ArrayList<String[]>();

then in the loop where you have

accounts.add(new Database(array[0],array[1],array[2]));

replace it with

accounts.add(array1);

Also, You never incremented J so your program will only get the first record.

If you have to use the Database class you have created, then you need to add a constructor that accepts those parameters.

Here:

BufferedReader in = new BufferedReader(new FileReader("filefullofmoney.txt"));
String line;
StringBuilder account = new StringBuilder();
List<Database> accounts = new ArrayList<Database>();

int count = 1;
while ((line = in.readLine()) != null) {
   account.append(line);
   account.append("---")

   if (count % 3 == 0) {
       Database data = new Database();
       data.accountName = account.toString().split("---")[0];
       data.pin = Integer.parseInt(account.toString().split("---")[1]);
       data.balance = Double.parseDouble(account.toString().split("---")[2]);
       accounts.add(data);
       account = new StringBuilder();
   }

   count++;
}

in.close();

Explanation:

The file is being read and every 3 lines (name, pin, balance), the data is added the the accounts List (% means modulus which returns the remainder when you divide). Since the pin and balance are not Strings, you have to parse the String to an integer and a double respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM