1

我正在尝试编写一个将文本文件读入数组列表的编码。但是,我不确定如何将我的文本文件解析为字符串以正确放入数组列表中。这是我需要使用的示例文本文件。

这应该是示例问题。

2
one
two
three
four
0
4
6

我的Java代码如下:

package javaapplication8;

import java.util.*;
import java.io.*;
public class JavaApplication8 {


public static void main(String[] args) throws IOException{

    Scanner inScan = new Scanner(System.in);

    String file_name;
    System.out.print("What is the full file path name?\n>>");
    file_name = inScan.next();

    Scanner fScan = new Scanner(new File(file_name));
    int numItems = Integer.parseInt(fScan.nextLine());
    ArrayList<String> Questions = new ArrayList<String>();

    for(int i=0; i < numItems; i++)
    {
        Questions.add(fScan.nextLine());
    }

    System.out.print("The array is: " + Questions);



}
4

1 回答 1

0

从您对numLines下面变量的评论中,您不需要从内容中解析整数,因此您可以删除该行:

int numItems = Integer.parseInt(fScan.nextLine());

然后将每一行输出到数组,您可以使用Scanner.hasNextLine()

while (fScan.hasNextLine()) {
   questions.add(fScan.nextLine());
}
于 2012-11-01T23:45:41.843 回答