从文本文件中随机读取
问题描述:
我刚开始开发android应用程序,突然发现很难从文本文件中随意读取一个单词,当单击按钮时。我试图将文本文件中的所有单词放入数组中并告诉它直到下一行(随机)显示该单词,但它似乎不起作用。我想知道如何从一个文本文件中逐一阅读和显示单词,并且每次点击一个按钮时随机!从文本文件中随机读取
答
你应该尝试将单词逐字分解并放入一个数组中。
答
通过读取文件到最后创建一个大字符串。 使用string.split将大字符串拆分为数组列表,并为拆分方法提供正确的拆分参数(“”或“,”)。 从阵列列表中随机输入,其中允许的最大随机数是arralist的大小。
答
用于显示单词数组中单词的示例代码。
大多数行的功能都写在注释中。
string words[]; // array for words.
/* code for reading text from text file and place words in text into words[] */
int sizeOfArray = numberOfWordsInArray; /* the value is set in the code of words placing into array */
Random rnd = new Random(); // random number generator
int index = rnd.nextInt(sizeOfArray); // nextInt returns random integer number between 0 and (sizeOfArray-1).
printf("%s\n",words[index]); // select a word by random number and display it.
答
我猜你每行只有一个单词。使用下面的代码读取文件并将其保存到列表中。
ArrayList<String> list = new ArrayList<String>();
try {
InputStream instream = openFileInput("yourfile.txt");
if (instream) {
BufferedReader buffreader = new BufferedReader(new InputStreamReader(instream));
String line;
while ((line = buffreader.readLine())) {
list.add(line);
}
}
instream.close();
} catch (java.io.FileNotFoundException e) {
}
将上面的代码放在onCreate方法中。现在使用import java.util.Random从列表中随机选择您的项目。将下面的代码放在OnClickListener中。
public Item anyItem()
{ private Random randomGenerator = new Random();
int index = randomGenerator.nextInt(list.size());
Item item = list.get(index);
System.out.println("Your Selected item is " + item");
return item;
}
现在你可以做任何事情从anyItem()方法上面返回的项目,希望它可以帮助你。
你能分享你当前的代码吗? – Tom 2014-09-05 10:09:36
阅读关于如何[在Android中阅读文本文件](http://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android)。我不认为你可以随意阅读一个文本文件,因为在阅读任何内容之前光标至少需要被设置。最好的方法来实现你想要的imho将是读取整个文本文件,将词存储在一个集合中,然后随机化该集合中的单词选择。 – m4rtin 2014-09-05 10:10:28
您将文本文件的单词存储到数组中,所以在“单词选择”和/或“显示单词”中出现错误。如何开发一个从单词阵列中随机显示单词的程序? – 2014-09-05 10:23:34