繁体   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