gpt4 book ai didi

java - 在已经从文本中随机选择一个单词后,如何从文本文件中打乱单词

转载 作者:行者123 更新时间:2023-12-03 17:58:06 24 4
gpt4 key购买 nike

我的文本文件中的单词已经随机打印出来了,但是我怎样才能让单词从文本中打乱。我有一个名为 ScrambleWords 的单独类(class)。我是坚持从另一个类调用 scrambleWord 方法。我的代码如下。

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);
}

}

最佳答案

要真正打乱单词,最好使用像列表这样的中间数据结构,这样可以更快地对数据进行排序。

例子:

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[]));
}

关于java - 在已经从文本中随机选择一个单词后,如何从文本文件中打乱单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31216374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com