我想要做的是,读取一个在一行中包含多个单词的文件,然后将每个单词添加到二维数组列表中。这应该是这样的 [[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);
}
}
文件中的文本看起来像这样
凯文美国黑客 沃兹尼亚克 美国黑客 美国黑客工作
最佳答案
你总是得到references.get(i),其中i=0,所以每当读取新行时, token 的插入就会从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);
}
}
关于java - 将文件读取到二维数组列表并将每个单词按行存储到数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8560963/