簡體   English   中英

在從文本中隨機選擇一個單詞后,如何從文本文件中加擾單詞

[英]How can I scramble words from a text file after already randomly choosing a word from text

我在文本文件中的單詞已經隨機打印出來,但是如何才能從文本中獲取單詞。 我有一個名為ScrambleWords的單獨類。 我堅持從另一個類調用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);
    }

}

要實際加擾這些單詞,最好使用像List這樣的中間數據結構來為自己提供一種更快捷的數據排序方法。

例:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM