如何使用Scanner从文本文件创建数组?

时间:2015-06-08 09:48:48

标签: java arrays syntax java.util.scanner

我刚开始学习Java,我正在尝试完成这项练习。

我已经了解了如何使用扫描仪从txt文件中提取信息(我认为)(我们只应该更改方法体)。但是,我不确定将信息传输到数组的正确语法。

我意识到它必须非常简单,但我似乎无法弄明白。有人可以指出我在语法和所需元素方面的正确方向吗?提前谢谢!

import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;

public class Lab02Task2 {

    /**
     * Loads the game records from a text file.
     * A GameRecord array is constructed to store all the game records.
     * The size of the GameRecord array should be the same as the number of non-empty records in the text file.
     * The GameRecord array contains no null/empty entries.
     * 
     * @param reader    The java.io.Reader object that points to the text file to be read.
     * @return  A GameRecord array containing all the game records read from the text file.
     */
    public GameRecord[] loadGameRecord(java.io.Reader reader) {

        // write your code after this line

        Scanner input = new Scanner(reader);
        for (int i=0; input.hasNextLine(); i++) {
            String inputRecord = input.nextLine();
            input = new Scanner(inputRecord);
            // array?
        }
        return null; // this line should be modified/removed after finishing the implementation of this method.
    }
}

4 个答案:

答案 0 :(得分:1)

如果您已有String个文件内容,可以说:

String[] words = content.split("\\s");

答案 1 :(得分:0)

您可以像这样解析字符串:

private ArrayList<String> parse(BufferedReader input) throws CsvException {
    ArrayList<String> data = new ArrayList<>();

    final String recordDelimiter = "\\r?\\n|\\r";
    final String fieldDelimiter = "\\t";

    Scanner scanner = new Scanner(input);
    scanner.useDelimiter(recordDelimiter);

     while( scanner.hasNext() ) {
        String line = scanner.next();
        data.add(line);
     }

     return data;
}

将逐行扫描输入文本。

答案 2 :(得分:0)

您可以使用ArrayList<String>,如下所示:

Scanner s = new Scanner(new File(//Here the path of your file));

ArrayList<String> list = new ArrayList<String>();

while (s.hasNext())
{
    list.add(s.nextLine());
}

如果你想获得ArrayList的某个项目的值,你只需要使用get函数进行引用,如下所示:

list.get(//Here the position of the value in the ArrayList);

所以,如果你想获得ArrayList的所有值,你可以使用循环来完成它:

for (int i = 0; i < list.size(); i++)
{
   System.out.println(list.get(i));
}

最后关闭Scanner

s.close();

我希望它会对你有所帮助!

答案 3 :(得分:0)

假设你的文件中的一行只包含一个游戏

 for (int i=0; input.hasNextLine(); i++) {
               String inputRecord = input.nextLine();
               input = new Scanner(inputRecord);

               String line=input.nextLine();

               arr[i]=line;
             }  
    return arr;
相关问题