My words from the text file are already printing out randomly, but how can I get the words to scramble from text. I have a seperate class called ScrambleWords. I'm stuck on calling the scrambleWord method from the other 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);
}
}
To actually scramble the words you would be better off using an intermediate data structure like a List to give yourself a quicker means for sorting 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[]));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.