发布
社区首页 >问答首页 >在java中使用分隔符填充数组

在java中使用分隔符填充数组
EN

Stack Overflow用户
提问于 2014-03-19 08:07:29
回答 2查看 62关注 0票数 0

我有一个用制表符分隔的文本文档。每一行都有相同类型的重复信息。当我使用hasNextLine()和一个计数器对行进行计数时,它只对一部分行进行计数。我仍然可以创建我得到的计数器大小的数组。当我使用for循环来填充数组时,结果是意想不到的。

以下是我所做工作的总结。

代码语言:javascript
代码运行次数:0
复制
    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 yellow0\n null1\n null2\n null3\n等等。

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

任何帮助都将不胜感激。我不经常使用useDelimiter,但据我所知,它将使'\t‘分隔标记,而不是空格和'\n’

EN

回答 2

Stack Overflow用户

发布于 2014-03-19 08:09:17

不要担心,使用它:

代码语言:javascript
代码运行次数:0
复制
final List<String> lines = Files.readAllLines(Paths.get("input.txt"),
    StandardCharsets.UTF_8);

然后,读取的行数就像lines.size()一样简单,您只需遍历列表来处理您的行数。

票数 1
EN

Stack Overflow用户

发布于 2014-03-19 08:12:55

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22493668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档