java - 将 ArrayList 拆分为多个 ArrayList

标签 java arrays file text arraylist

我想知道如何将以下数据拆分为多个列表。这是我的输入(来自文本文件,此处重新创建的示例):

aaaa bbbb cccc,ccc,cccc

aaaa-- bbbb

aaaa bbbb cccc-

aaaa bbbb cccc,ccc

aaaa-

aaaa bbbb ccc,cccc,cccc

文本的每个部分之间用空格分隔。我需要编写的代码应该创建三个列表,由文本文件中每行的每个条目的 a、b 和 c 组组成,同时忽略带有“-”的任何行。所以,我的 3 个数组应该填充如下:

Array1: aaaa, aaaa, aaaa
Array2: bbbb, bbbb, bbbb
Array3: (cccc,ccc,cccc),(cccc,ccc),(ccc,cccc,cccc)

添加括号以表明第三个数组应包含所有列出的 c 值 a、b 和 c 都包含从文本文件导入的字符串。到目前为止,这是我的代码:

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

public class SEED{

public static void main (String [] args){

    try{

        BufferedReader in = new BufferedReader(new FileReader("Curated.txt"));
        String temp;
        String dash = "-";
        int x = 0;
        List<String> list = new ArrayList<String>();
        List<String> names = new ArrayList<String>();
        List<String> syn = new ArrayList<String>();
        List<String> id = new ArrayList<String>();


        while((temp = in.readLine()) != null){

            if(!(temp.contains(dash))){

                list.add(temp);

                if(temp.contains(" ")){

                    String [] temp2 = temp.split(" ");
                    names.add(temp2[0]);
                    syn.add(temp2[1]);
                    id.add(temp2[2]);

                }else{

                    System.out.println(temp);

                }//Close if

                System.out.println(names.get(x));
                System.out.println(syn.get(x));
                System.out.println(id.get(x));

            x++;


            }//Close if


        }//Close while

    }catch (Exception e){

e.printStackTrace();
        System.exit(99);

    }//Close try

}//Close main

}//Close class

但我的输出始终是:什么也没有。如何正确地将这些值保存到 3 个单独的数组或 ArrayList 中?

最佳答案

您正在引用 list.get(x),但您的 x++list.add 将不会同步,如果你读了一行没有破折号的行。因此 (x) 不是正确的引用。

你为什么这样做:

String [] temp2 = list.get(x).split(" ");

而不是:

String [] temp2 = temp.split(" ");

编辑

尝试:

if(!(temp.contains(dash))){

            list.add(temp);

            if(temp.contains(" ")){

                String [] temp2 = temp.split(" ");
                names.add(temp2[0]);
                syn.add(temp2[1]);
                id.add(temp2[2]);
            }else{

                System.out.println(temp);

            }//Close if

        }//Close if

for(int x = 0; x < names.size(); x++) {

            System.out.println(names.get(x));
            System.out.println(syn.get(x));
            System.out.println(id.get(x));
}

关于java - 将 ArrayList 拆分为多个 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24442086/

相关文章:

c++ - 使用 memcpy 复制二维数组?

php - 带有特殊字符的文件名,如 "é"NOT FOUND

python - 比较两个文件的相似性,而不是常见问题

c - 将 fopen 与 temp 系统变量一起使用

java - Guava 基于键的信号量与 ConcurrentHashMap 中的信号量

java - 如何使用 JMX 客户端列出所有 MBean

c# - 如何将 Regex.Matches 放入数组中?

java - 根据 JSTL 的键从 hashmap 中获取值

java - "Unreleased Resource: Database"确认问题

ios - += 和 append 将单个项目添加到数组的区别?