繁体   English   中英

在Java中使用定界符填充数组

[英]Filling in an array using a delimiter in java

我有一个由标签分隔的文本文档。 每行都重复相同类型的信息。 当我使用hasNextLine()和计数器对行进行计数时,它仅对行的一部分进行计数。 我仍然可以创建我得到的计数器大小的数组。 当我使用for循环填充数组时,结果出乎意料。

这是我所做的摘要。

    import java.util.*;
    import java.io.*;
    public class Test {
        public static void main(String[] args) {
            try {
                Scanner input = new Scanner(new File("input.txt"));
                int lines = 0;
                input.nextLine(); //for the header of the table
                while(input.hasNextLine()) {
                    lines++;
                    input.nextLine();
                }
                System.out.println(lines);//here I don't get the total amount
                String[] colors = new String[lines];
                int[] number = new int[lines];
                fillArray(colors, number);
                System.out.println(colors[i] + i);
            }
            catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        public static void fillArray(String[] color, int[] numbers) {
            try {
                Scanner input = new Scanner(new File("input.txt"));
                input.nextLine(); //for table header
                input.useDelimiter("\\t");
                for(int i = 0; i < color.length; i++) {
                    color[i] = input.next();
                    input.next(); //info i'm not using
                    numbers[i] = input.nextInt();
                    input.nextLine(); //consumes '\n'
                }
             }
             catch (Exception e) {
                 System.out.println(e.getMessage());
             }
         }
    }

它可以编译,但是我的结果如下所示:

null \\ n黄色0 \\ n null1 \\ n null2 \\ n null3 \\ n等。

它还显示正确的颜色和数字; 但仅适用于一行。

任何帮助,将不胜感激。 我没用过useDelimiter,但据我了解,它将使'\\ t'成为单独的标记,而不是空白和'\\ n'

不要打扰,使用它:

final List<String> lines = Files.readAllLines(Paths.get("input.txt"),
    StandardCharsets.UTF_8);

这样,读取的行数就和lines.size()一样容易,您只需要遍历列表即可处理行。

您可以使用OpenCSV http://opencsv.sourceforge.net/#custom-sepators 使用它来实施CSV Reader程序真的很容易。

暂无
暂无

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

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