簡體   English   中英

如何對從文本文件中隨機選擇的單詞進行加擾

[英]How to scramble a word that is picked randomly from a text file

我正在嘗試編寫一個程序,該程序從文本文件中選擇一個隨機單詞,對其進行加擾,並允許用戶通過一次交換2個索引位置來對其進行加擾。

我將程序抓到了從文本文件中抓取一個隨機單詞並用它上面的索引號打印出來的程度。

我在弄清楚如何:

  1. 在屏幕上打印出來之前先弄亂單詞,然后
  2. 如何使用戶能夠一次通過交換2個索引來循環直到單詞未加擾。

我可以編寫一種可以執行這些操作的方法嗎?

到目前為止,這是我的代碼。

import java.io.*;
import java.util.*;

public class Midterm { // class header

    public static void main(String[] args) { // Method header

        int option = 0;
        Scanner input = new Scanner(System.in);
        int scrambled;
        int counter = 0;
        int index1;
        int index2;     

        String[] words = readArray("words.txt");
        /*
         * Picks a random word from the array built from words.txt file. Prints
         * index with word beneath it.
         */
        int randWord = (int) (Math.random() * 11);

        for (int j = 0; j < words[randWord].length(); j = j + 1) {
            System.out.print(j);
        }

        System.out.print("\n");     
        char[] charArray = words[randWord].toCharArray();
        for (char c : charArray) {          
            System.out.print(c);
        }
        /*
         * Prompt the user for input to play game or quit.
         */
        System.out.println("\n");
        System.out.println("Enter 1 to swap a par of letters.");
        System.out.println("Enter 2 to show the solution and quit.");
        System.out.println("Enter 3 to quit.");     

        if (input.hasNextInt()) {
            option = input.nextInt();
            counter++;          
        }
        else {
            option = 3;
        }
        System.out.println("");

        if (option == 1) {
            System.out.println("Enter the two index locations to swap separated by a space. ");
            index1 = 0;
            index2 = 0;
            if (input.hasNextInt()) {
                index1 = input.nextInt();
                }
            else {
                System.out.println("Please enter only numbers.");
            }

            if (input.hasNextInt()) {
                index2 = input.nextInt();
                }
            else {
                System.out.println("Please enter only numbers.");
            }
        } 
        }   



    // end main

    public static String[] readArray(String file) {
        // Step 1:
        // Count how many lines are in the file
        // Step 2:
        // Create the array and copy the elements into it

        // Step 1:
        int ctr = 0;
        try {
            Scanner s1 = new Scanner(new File(file));
            while (s1.hasNextLine()) {
                ctr = ctr + 1;
                s1.nextLine();
            }
            String[] words = new String[ctr];

            // Step 2:
            Scanner s2 = new Scanner(new File(file));
            for (int i = 0; i < ctr; i = i + 1) {
                words[i] = s2.next();

            }
            return words;
        } catch (FileNotFoundException e) {

        }
        return null;

    }
}

您正在錯誤地讀取文件。

public static String[] readArray(String file) {
    int ctr = 0;
    try {
        Scanner s1 = new Scanner(new File(file));
        while (s1.hasNext()) {
            ctr = ctr + 1;
            s1.next();
        }
        //..rest of code

我對您的代碼進行了一些相當大的修改,包括添加了加擾器方法。 該程序幾乎是完美的,只是您的文件“ words.txt”不能包含重復字母的單詞。 例如,黃色,綠色和紫色無法正確解讀,但是白色,灰色,藍色,橙色或紅色將可以正常工作。 除此之外,該程序運行良好。 它選擇一個隨機單詞,然后在求解后選擇另一個單詞,將最后一個單詞更改為null,這樣就不會再次被選中。 這是程序:

import java.io.*;
import java.util.*;

public class Experiments { // class header

    private static String[] words = readArray("/Users/UserName/Desktop/words.txt"); //change to your location of the file

    public static void main(String[] args) { // Method header
        int option = 0;
        Scanner input = new Scanner(System.in);
        int counter = 0;
        String scrambledWord;
        int index1;
        int index2;     

        Random rand = new Random();
        int randWord = rand.nextInt(words.length);

        for (int j = 0; j < words[randWord].length(); j += 1) {
            System.out.print(j);
        }

        System.out.print("\n");     
        scrambledWord = scrambler(words[randWord]);
        System.out.println(scrambledWord);     

        System.out.println("\n");
        System.out.println("Enter 1 to swap a pair of letters.");
        System.out.println("Enter 2 to show the solution and quit.");
        System.out.println("Enter 3 to quit."); 
        option = input.nextInt();

        if (option == 1) {
            while (!scrambledWord.equals(words[randWord])) {
                index1 = 0;
                index2 = 0;
                boolean validOption = false;
                System.out.println("Enter the two index locations to swap separated by a space.");
                while (!validOption) {
                    if (input.hasNextInt()) {
                        index1 = input.nextInt();
                        index2 = input.nextInt();  
                        validOption = true;
                    }
                    else {
                        System.out.println("Please enter only numbers.");
                        validOption = false;
                        break;
                    }
                }
                String letter1 = scrambledWord.substring(index1, index1+1);
                String letter2 = scrambledWord.substring(index2, index2+1);
                System.out.println("replacing " + letter1 + " with " + letter2 + "...");
                if (index1 < index2) {
                    scrambledWord = scrambledWord.replaceFirst(letter2, letter1);                 
                    scrambledWord = scrambledWord.replaceFirst(letter1, letter2); 
                } else {
                    scrambledWord = scrambledWord.replaceFirst(letter1, letter2);                 
                    scrambledWord = scrambledWord.replaceFirst(letter2, letter1); 
                }
                System.out.println();
                for (int j = 0; j < words[randWord].length(); j += 1) {
                    System.out.print(j);
                }
                System.out.println("\n"+scrambledWord);
                System.out.println();
                counter++;
                if (scrambledWord.equals(words[randWord])){
                    System.out.println("You did it! The word was " + words[randWord]);
                    System.out.println("You got it with " + counter + " replacements!");
                    words[randWord] = null;
                    if (words.length == 0){
                        System.out.println("I'm all out of words. You win!");
                        System.exit(0);
                    } else {
                        main(args);
                    }
                }
            } 

        } else if (option == 2) {
            System.out.println(words[randWord]);
            System.exit(0);
        } else {
            System.exit(0);
        }
        input.close();
   }   

    //scrambles the word given to it
    private static String scrambler(String word) { 
        String scrambled = "";
        Random rand = new Random();
        int length;
        int index;
        String letter;
        String firststring;
        String secondstring;

        while (word.length()>0) {
            length = word.length();
            index = rand.nextInt(length);
            letter = word.substring(index, index+1);
            firststring = word.substring(0, index);
            secondstring = word.substring(index+1);
            word = firststring + secondstring;
            scrambled += letter;
        }
        return scrambled;
    }

    public static String[] readArray(String file) {
        int ctr = 0;
        try {
            Scanner s1 = new Scanner(new File(file));
            while (s1.hasNextLine()) {
                ctr = ctr + 1;
                s1.nextLine();
            }
            String[] words = new String[ctr];

            // Step 2:
            Scanner s2 = new Scanner(new File(file));
            for (int i = 0; i < ctr; i = i + 1) {
                words[i] = s2.next();

            }
            return words;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
        }
}

這是words.txt文件中的單詞列表(我幾乎記下了突然出現的沒有重復字母的所有內容):

orange
red
brown
black
white
blue
tiger
horse
bugs
stack
overflow
pathfinder
extra
zealous
wisdom
under
above
death
life
second
first
frost
forest

這些顯然不是唯一可以輸入的單詞,您可以根據需要添加任意數量的單詞,只要它們沒有兩次出現同一字母即可。

暫無
暫無

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

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