I'm reading text document file and displaying it on screen word by word. On button click it displays next word by random but some times it will repeat some words. So I did some research and I figured that it's best for me to use shuffle
. How can I manage that. Here's my code:
public void Random_Word(){
String text = "";
try {
InputStream is = getAssets().open("challenges.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException ex) {
ex.printStackTrace();
}
String[] separated = text.split("\n");
int size = separated.length;
int randomNum = (int) (Math.random() * size - 1);
String randomWord = separated[randomNum];
word.setText(randomWord);
}
CodePudding user response:
if your main problem is repeating words then I have an alternative solution for that
you can create an array of strings and every time you generate a new random word check if it is already in the list. if it exists then you can generate a new random word else you can display it.
let's see how:- create an array in your java class or activity.
ArrayList<String> words_array = new ArrayList<>();
and in your void Random_word();
you can add this code.
public void Random_Word(){
String text = "";
try {
InputStream is = getAssets().open("challenges.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException ex) {
ex.printStackTrace();
}
String[] separated = text.split("\n");
int size = separated.length;
int randomNum = (int) (Math.random() * size - 1);
String randomWord = separated[randomNum];
if(words_array.contains(randomWord)){
//word already exists so call method again
Random_word();
}else{
//add word in array and display it
words_array.add(randomWord);
word.setText(randomWord);
}
}
I know this is not the answer to your question but this can solve your problem.