How can I scramble words from a text file after it has randomly selected a word from text
My words from the text file are already printing randomly, but how can I get the words to scramble from the text. I have a separate class called ScrambleWords. I am stuck when calling the scrambleWord method from another class. My code is below.
public class WordShuffle extends ScrambleWords {
protected Scanner file;
protected ArrayList<String> words = new ArrayList<String>();
public void openFile(){
try {
file = new Scanner(new File("words.txt"));
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (Exception e){
System.out.println("IOEXCEPTION");
}
}
public void readFile(){
Random r = new Random();
while(file.hasNextLine()){
words.add(file.nextLine());
}
String randomWord = words.get(r.nextInt(words.size()));
Collections.shuffle(words);
System.out.println(randomWord);
//}
}
public void closeFile(){
file.close();
}
public static void main(String[] args) {
//ArrayList<String> inputString = words;
WordShuffle shuff = new WordShuffle();
//ScrambleWords mix = new ScrambleWords();
shuff.openFile();
System.out.print("Before: ");
shuff.readFile();
//System.out.println("After: ");
shuff.closeFile();
}
}
public class ScrambleWords {
public static String scrambleWord(Random r, String inputString){
//convert string to char array
char a[] = inputString.toCharArray();
for(int i = 0; i < a.length-1; i++){
int j = r.nextInt(a.length-1);
//swap letters
char temp = a[i]; a[i] = a[j]; a[j] = temp;
}
return new String(a);
}
}
+3
source to share
1 answer
To really cross words, you'd be better off using an intermediate data structure like List to give you a faster way to sort the data.
Example:
public static String scrambleWords(Random r, String curWord) {
List<Character> theWord = new ArrayList<>(curWord.length());
for (int i = 0; i < theWord.size(); i++) {
theWord.add(curWord.charAt(i);
}
Collections.shuffle(theWord);
return new String(theWord.toArray(new Character[]));
}
0
source to share