簡體   English   中英

如何輸出隨機選擇的單詞並從文本文件java中打亂同一個單詞

[英]How to output a randomly chosen word and scramble the same word from a text file java

以下是我的輸出。 我希望下面的混亂單詞與我的隨機單詞相同。 現在,它從文本文件中打印出兩個不同的單詞,我希望它是相同的,除了一個是加擾的,另一個是普通的。 下面是我的代碼。

在此處輸入圖片說明

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;


public class ScrambleWords {

    private static Scanner file;
    private static List<String> words = new ArrayList<String>();
    private static List<Character> characters = new ArrayList<>();

    public static void openFile() {

        try {
            file = new Scanner(new File("words.txt"));

        } catch (FileNotFoundException e) {
            System.out.println("File Not Found");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("IOException");
        }
    }

    public static String randomWord() {

        Random r = new Random();

        while(file.hasNext()) {
            words.add(file.next());
        }

        Collections.shuffle(words);
        String randomWord = words.get(r.nextInt(words.size()));

        return randomWord;
    }

    public static String readScramble(String randomWord) {

        for(char ch : randomWord.toCharArray()) {
            characters.add(ch);
        }

        Collections.shuffle(characters);
        StringBuilder sb = new StringBuilder();

        for(char ch: characters) { 
            sb.append(ch);
        }
        return sb.toString();
    }

    public static void main(String[] args) {

        openFile();

        String scramble = readScramble(randomWord());
        System.out.println("Scramble Word is: " + scramble);

        String random = randomWord();
        System.out.println("Random Word is: " + random);

    }

}

您將獲得兩個不同的隨機詞實例。 修改您的代碼,如下所示:

 openFile();

    String word = randomWord();
    String scramble = readScramble(word);
    System.out.println("Scramble Word is: " + scramble);

    String random = word;
    System.out.println("Random Word is: " + random);

更改您的主要方法:

  public static void main(String[] args) {

    openFile();

    String word = randomWord();

    String scramble = readScramble(word);
    System.out.println("Scramble Word is: " + scramble);

    System.out.println("Random Word is: " + word);

}

順便說一句,也許您應該將此代碼發布在代碼審查堆棧交換中。

您兩次調用randomWord() ,從而生成兩個隨機詞。 根據“隨機”的定義,您不能兩次期望相同的單詞。 將您的主要方法更改為

String w = randomWord();

然后打印w及其加擾的版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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