【问题标题】:Java Reading a txt that has different numbers in its column file and store data in an arraylistJava读取列文件中具有不同数字的txt并将数据存储在arraylist中
【发布时间】:2021-03-23 01:48:07
【问题描述】:

大家好,我在下面有一个 txt 文件,我需要存储第二列数据,但它给了我一个错误,因为有些行有 1,有些有 2,有些每行有 3 个输入。我该如何解决这个问题?


5
3 4
3 4
3 3
3 4
3 3
3 4
3 3
3 2
3 4
3 3
3 2
3 1
3 4
3 3
3 2
3 1
3 0
1
2
5 3 4
3 4
3 4
3 3
3 4
3 3
3 4
3 3
3 2
3 4
3 3
3 2
3 1
3 4
3 3
3 2
3 1
3 0
1
2
5 4 6
4 4
4 4
4 4
4 4
4 4
4 4
4 3
4 3
4 3
4 3
4 4
4 4
1
2
5 4 6
0

这就是我所做的,我试图区分大小和其他方式,但仍然无法得到答案......

String line = "";

ArrayList<String> numbers= new ArrayList<String>();

try {

    String sCurrentLine;
    br = new BufferedReader(new FileReader("input1.txt"));
    int n = 0;

    while ((sCurrentLine = br.readLine()) != null) {
        String[] arr = sCurrentLine.split(" ");
        int size = arr.length;

        List<String> list = ConvertToList.convertArrayToList(arr);
        List<Integer> listOfInteger = convert.convertStringListToIntList(list, Integer::parseInt);
        if (list.size() == 2) {
            line.split("\\s+");
            numbers.add(line.split("\\s+")[0]);
            System.out.println(numbers);
        }
    }
} catch(Exception e) {
    e.printStackTrace();
}

【问题讨论】:

    标签: java file arraylist split txt


    【解决方案1】:

    您不需要再次拆分线路。第一次拆分行时,检查结果数组的长度是否为2。如果是,请将arr[1] 添加到numbers

    while ((sCurrentLine = br.readLine()) != null) {
        String[] arr = sCurrentLine.split(" ");                
        if (arr.length >= 2) {
            numbers.add(arr[1]);
            System.out.println(numbers);
        }
    }
    

    更新:

    根据您的评论,我为您提供以下使用您的列表的代码:

    while ((sCurrentLine = br.readLine()) != null) {
        String[] arr = sCurrentLine.split(" ");
        List<String> list = ConvertToList.convertArrayToList(arr);
        List<Integer> listOfInteger = convert.convertStringListToIntList(list, Integer::parseInt);
        if (listOfInteger.size() >= 2) {
            numbers.add(listOfInteger.get(1));
        }          
    }
    System.out.println(numbers);
    

    您可以将System.out.println(numbers); 保留在while 循环的内部或外部,具体取决于您希望如何打印numbers

    【讨论】:

    • 不应该是 if (arr.length >= 2)
    • @rishavprasher - 要求是:I need to store the second column data...
    • 但是在分割长度之后我们可以大于2。例如如果是 3,那么我们必须将数字存储在第 2 列对吗?
    • @rishavprasher - 你是对的。更新了答案。
    • @ArvindKumarAvinash 我发布了一个新代码,当我尝试你的建议时,我的代码是如何工作的。你能看到他们吗?
    【解决方案2】:

    如果您只想读取和保存第二列而不是使用索引 1 获取第二列中的数据。(在您的 while 循环之后。)

    String secondCol = sCurrentLine.split(" ")[1];
    

    如果您在 2 列中没有值,则会抛出异常,您应该使用简单的 try catch 来处理。 最后将其转换为 int 并存储在您的列表中。跟随。

    listOfInteger.add(Integer.parseInt(secoundCol));
    

    希望它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2020-05-25
      • 2013-03-24
      相关资源
      最近更新 更多