[英]How can I scramble words from a text file after already randomly choosing a word from text
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.
我有一个名为ScrambleWords的单独类。 I'm stuck on calling the scrambleWord method from the other class.
我坚持从另一个类调用scrambleWord方法。 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. 要实际加扰这些单词,最好使用像List这样的中间数据结构来为自己提供一种更快捷的数据排序方法。
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[]));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.