从 Java 中的文本文件中读取不同的变量

Reading different variables from text file in Java

所以我有这样的文字:

16783 BOB ARUM 30.5 10.00

其中很多在文本文件的不同行上作为(long,string,string,double,double) 我想将这些变量存储在一个数组中,到目前为止我有:

public class Main {

public static void main(String[] args){

    ArrayList<String> ArrEmployee = new ArrayList<String>(); // create array for employees

    try {
        Scanner txtIn = new Scanner(new File("payroll.txt"));
    } 
    catch (FileNotFoundException e) {

    }

}}

我遇到的问题是我想不出一种方法来有效地将这些值存储在我的 arrEmployee 数组中,以便我以后可以使用它们。到目前为止,我发现使用构造函数创建不同的 class 可能会有所帮助,但我很难理解如何访问数组中的对象。

例如,如果我只想要行尾的双精度数,假设它现在是一个存储在数组中的对象,我将如何访问那个特定的双精度数?

将您的输入作为字符串写入数组列表可能看起来很像:

for (line in textFile) {
    ArrayList<String> arrList = new ArrayList();
    arrList.addAll(Array.toList(line.split(" ")));
}

显然,要使这些字符串有用,您需要将它们转换为实际类型,例如:

double test = Double.parseDouble(arrList[3]);

这就是您如何访问存储在数组中的对象的变量:

arrEmployee[2] = new Employee();//im leaving out the args, since i don't know what they would be

String name = arrEmployee[2].getName();//this is the name of the second employee in the array

这只是一个示例代码,其中包含很多实现,但我认为它回答了您的问题。

创建一个雇员 class 会很有帮助,所以假设您创建了一个具有多个实例变量的雇员。如果将最后一个双精度值存储为 for 循环中的实例变量之一,则稍后可以通过从对象中调用它来检索该值。

如果您选择使用这种方式,则必须更改 ArrayList 以改为保存 Employees,因此必须更改从文件输入的方式。

因此,如果您有一个 Employee class,其构造函数接受 (long,string,string,double,double) 并且最后一个 double 变量名为 'D3',您可以使用:

public class test {

public static void main(String[] args) {

    ArrayList<Employee> ArrEmployee = new ArrayList<Employee>(); // create array for employees

    try {
        Scanner txtIn = new Scanner(new File("payroll.txt"));
        while (txtIn.hasNext()) {
            Double D1 = txtIn.nextDouble();
            String S1 = txtIn.next();
            String S2 = txtIn.next();
            Double D2 = txtIn.nextDouble();
            Double D3 = txtIn.nextDouble();
            ArrEmployee.add(new Employee(D1,S1,S2,D2,D3));
        }
    } catch (FileNotFoundException e) {

    }
    System.out.println(ArrEmployee.get(0).getD2());//Note here how you can use method getD2() on the method get(0) of your ArrayList, if the list's type is Employee and you've implemented getD2() to return the last double

}

}