【问题标题】:Reading file to 2d arraylist and store each words in line to array list将文件读取到二维数组列表并将每个单词逐行存储到数组列表
【发布时间】:2011-12-19 11:55:06
【问题描述】:

我想要做的是,在一行中读取一个包含多个单词的文件,然后将每个单词添加到二维数组列表中。这应该是这样的 [[kevin,kevin,kevin][jobs,jobs,jobs]]

下面的代码运行良好,但它确实像这样 [[kevin,kevin,kevin,jobs,jobs,jobs]]

应该使用嵌套的for来完成,但是有人可以帮忙吗?

public void getReference() throws IOException
    {
        String line=null;

            connectRead("computer");
            //this is a method that reads a file in a format kevin kevin kevin kevin
            try
            {
                reference.add(new ArrayList<String>());
                while ((line=bufferedReader.readLine())!=null)
                {
                    st = new StringTokenizer(line); 

                    for ( int i = 0 ; i < st.countTokens() ; i++)
                    {       
                        reference.get(i).add(st.nextToken());
                        reference.get(i).add(st.nextToken());
                        reference.get(i).add(st.nextToken());
                        reference.get(i).add(st.nextToken());  
                    }

                }
                System.out.println(reference);

                bufferedReader.close();
            }
            catch ( IOException e )
            {
               System.out.println(e);
            }      

    }

文件中的文本看起来像这样

凯文美国黑客 沃兹尼亚克美国黑客 美国黑客工作

【问题讨论】:

    标签: java arraylist multidimensional-array


    【解决方案1】:

    您总是会得到references.get(i),其中i=0,因此每当读取新行时,都会从ArrayList 的第0 个索引处开始插入标记。

    试试这个,但是这个结构对我来说有点混乱。可能显示输入文件的结构有助于使代码更好。

    public void getReference() throws IOException
    {
        String line=null;
    
            connectRead("computer");
            //this is a method that reads a file in a format kevin kevin kevin kevin
            try
            {
                reference.add(new ArrayList<String>());
                int indexOfReferences =0 ;
                while ((line=bufferedReader.readLine())!=null)
                {
                    st = new StringTokenizer(line); 
    
                    for ( int i = 0 ; i < st.countTokens() ; i++)
                    {       
                        reference.get(indexOfReferences).add(st.nextToken());
                    }
                   indexOfReferences++;
    
                }
                System.out.println(reference);
    
                bufferedReader.close();
            }
            catch ( IOException e )
            {
               System.out.println(e);
            }      
    
    }
    

    【讨论】:

    • 更改代码后出现此错误“线程中的异常”main“java.lang.IndexOutOfBoundsException: Index: 1, Size: 1”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多