如何从android中的文本文件加载随机行?

时间:2013-08-09 23:54:11

标签: android

我有这段代码;

Scanner s = new Scanner(getResources().openRawResource(R.raw.game));

try {
    while (s.hasNextLine()) {

        System.out.println(s.nextLine());

    }
} finally {
    s.close();
} 

如何从这段代码加载随机行?

感谢。

3 个答案:

答案 0 :(得分:2)

您可以将这些行加载到另一个数据结构中,例如ArrayList,然后使用Random生成随机索引号。

以下是将其放入ArrayList的一些代码:

Scanner s = new Scanner(getResources().openRawResource(R.raw.game));
ArrayList<String> list = new ArrayList<String>();

try {
    while (s.hasNextLine()) {
        list.add(s.nextLine());      
    }
} finally {
    s.close();
} 

此代码将返回一个随机行:

public static String randomLine(ArrayList list) {
    return list.get(new Random().nextInt(list.size()));
}

答案 1 :(得分:1)

首先将所有文件从文件加载到String数组中,然后从String数组中随机选择其中一个。

答案 2 :(得分:1)

让我们假设您收集了String数组lines

int randomLine = (int)(Math.random()*lines.length);

你有随机线。

编辑:哦,你可以只使用String[]