繁体   English   中英

需要帮助来从文本文件中读取行并将其添加到ArrayList

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

对于我的作业,我应该创建一个ATM / Teller程序,将用户帐户存储在一个文本文件中。 我需要阅读文本文件并将其某些部分存储在数组列表中的帮助。

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;
}

我遇到麻烦的部分是account.add(new Database(array [0],array [1],array [2]));

基本上,我的文本文件将以这种方式格式化:

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

我希望能够将每个帐户的3行文本添加到arraylist的一个元素中。

我不确定我有多少可以实际工作,因为我无法编译它。

任何帮助是极大的赞赏。 谢谢

您的代码存在一些问题:

  • 您没有为Database类指定的构造函数(应将其命名为Account )。
  • 您无需对这些行进行子串化,因此可以使用所有的“ Database#”前缀。
    • 我想问一下,为什么还要在其中加上前缀? 他们似乎多余。
  • 您不会将string s强制转换为实际的数据类型( intdouble )。
  • 您只需要循环一次内容就可以循环两次。
  • 您没有适当的异常处理; 您永远不要将所有内容都包装在一个catch(Exception)

您的代码的可能解决方案可能是这样(我尚未测试它是否确实有效):

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;
    }
}

您正在使用array1并且array选择一个,它将进行编译。

另外,您应该将这两个while循环组合在一起。 提示:您不需要知道numberOfLines

将类重命名为Account而不是Database

然后:readLine()方法将返回整行,因此:

Account1 Martijn Courteaux

将是一行。 要从中获取名称,可以使用String.substring()

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

对其他两个值执行相同的操作:

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

然后使用这些值将它们传递给构造函数:

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

你应该改变

Database[] accounts = new Database[numberOfLines];

成为

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

然后在循环中

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

替换为

accounts.add(array1);

另外,您永远不会增加J,因此您的程序只会得到第一条记录。

如果必须使用创建的Database类,则需要添加一个接受那些参数的构造函数。

这里:

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();

说明:

正在读取文件,并且每三行(名称,大头针,余额)将数据添加到帐户列表中(%表示模数,除后将返回余数)。 由于大头针和天平不是字符串,因此必须分别将字符串解析为整数和双精度型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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