简体   繁体   English

使用数组随机组合字符串

[英]Random combination of strings using arrays

I'm trying to figure out how to combine 2 random Strings entered by the user. 我正在试图弄清楚如何组合用户输入的2个随机字符串。 This program is kind of like a Mad Libs game but instead it is for creating a poem. 这个节目有点像疯狂的自由游戏,但它是用来创作一首诗。 I first start by asking the user to enter the number of nouns to use, and then storing them into an array, and follow by asking the amount of adjectives, which also are stored in an array. 我首先要求用户输入要使用的名词数量,然后将它们存储到数组中,然后询问形容词的数量,这些形容词也存储在数组中。

Precisely what is asked is as follows: 确切地说,问题如下:

Generate your poem by choosing at random combinations of noun and adjectives. 通过选择名词和形容词的随机组合来产生你的诗。 You are not allowed to pick a noun or an adjective again until you have used all sets of noun and adjectives that the user has provided, respectively. 在分别使用用户提供的所有名词和形容词组之前,不允许再次选择名词或形容词。

Now I am asked to generate a poem by combining the entered nouns and adjectives, but the generator needs to be random. 现在我被要求通过组合输入的名词和形容词来生成一首诗,但是生成器需要是随机的。 How would I do this? 我该怎么做? So far my program is as follows: 到目前为止,我的计划如下:

import java.util.Scanner;
public class A3Question1 
{

public static void main(String[] args) 
{
    Scanner keyboard = new Scanner(System.in);
    boolean loop1 = false;
    boolean loop2 = false;
    boolean loop3 = false;
    int numNouns = 0, numAdjectives = 0;
    String[] nouns = new String[numNouns];
    String[] adjectives = new String[numAdjectives];

    System.out.println("-----------------------------------------");
    System.out.println("           Let's write a poem!           ");
    System.out.println("-----------------------------------------");
    System.out.println();

    while (!loop1)
    {
        System.out.print("How many nouns? (min 3): ");
        numNouns = keyboard.nextInt();

        if (numNouns < 3)
        {
            continue;
        }
        else
        {
            loop1 = true;
        }

        System.out.println("Enter " + numNouns + " nouns: ");
        nouns = new String[numNouns];

        for (int i = 0; i < numNouns; i++)
        {
            nouns[i] = keyboard.next();
        }
    }
    while (!loop2)
    {
        System.out.print("How many adjectives? (min 3): ");
        numAdjectives = keyboard.nextInt();

        if (numAdjectives < 3)
        {
            continue;
        }
        else
        {
            loop2 = true;
        }

        System.out.println("Enter " + numAdjectives + " adjectives: ");
        adjectives = new String[numAdjectives];

        for (int j = 0; j < numAdjectives; j++)
        {
            adjectives[j] = keyboard.next();
        }

        while (!loop3)
        {
            System.out.println("\n-----------------------------------");
            System.out.println("        Here is my Java Poem!         ");
            System.out.println("           **LOOK AROUND**            ");
            System.out.println("-----------------------------------");
            System.out.println();

            for (int i = 0; i < numNouns && i < numAdjectives; i++)
            {                   
                int num1 = (int) (Math.random() * numNouns); 
                int num2 = (int) (Math.random() * numAdjectives);
                System.out.println(nouns[num1] + adjectives[num2]);
            }

            System.out.println("\nAnother poem? (y/n): ");
            String again = keyboard.next();

            if (again.charAt(0) == 121 || again.charAt(0) == 89)
            {
                continue;
            }
            else
            {
                loop3 = true;
            }
        }

        System.out.println("Thank you for using POEM GENERATOR! Have a good day!");         
    }       
    keyboard.close();
}

} }

Sample output: 样本输出:

https://postimg.org/image/6ogwggw9f/ https://postimg.org/image/6ogwggw9f/

Edit**: I cleaned up the code and combined the arrays randomly together. 编辑**:我清理了代码并将数组随机组合在一起。 However, the random arrays generated cannot be reused again and I'm trying to figure out how to avoid this problem. 但是,生成的随机数组不能再次重用,我试图弄清楚如何避免这个问题。 I also need to indent the poem properly as seen in the picture. 如图所示,我还需要正确缩进这首诗。 For example, the first output has no space, second output has a tab, and third has two tabs. 例如,第一个输出没有空格,第二个输出有一个选项卡,第三个输出有两个选项卡。

Use a Random object to select a random index in your arrays. 使用Random对象选择数组中的随机索引。 A second random could select a whether the noun or adjective array should be picked from. 第二个随机可以选择是否应该从中挑选名词或形容词数组。

public String randomPoem(String[] nouns, String[] adjectives) {
    Random random = new Random();
    ArrayList<String> nounList = new ArrayList<>(Arrays.asList(nouns));
    ArrayList<String> adjList = new ArrayList<>(Arrays.asList(adjectives));
    String value = "";
    if (random.nextBoolean()) {
        int index = random.nextInt(nounList.size());
        value += nounList.remove(index);
    } else {
        int index = random.nextInt(adjList.size());
        value +=  adjList.remove(index);
    }
    return value;
}

You have to randomize the arrays in place. 您必须将数组随机化。 A simple method to do that is to pick any 2 elements in the array and swap them with each other. 一个简单的方法是选择数组中的任何2个元素并相互交换。 Do that enough times and you will have a randomized array. 做足够多次,你将有一个随机阵列。

Here's a sample 这是一个样本

package com.example;

import java.util.Random;

public class RandomTest {
    public static void main(String[] args) {
        String[] nouns = {"roses", "tulips", "grass"};
        shuffle(nouns, 50);
        String[] adjectives = {"red", "lovely", "gorgeous", "green"};
        shuffle(adjectives, 50);

        for(int i = 0; i < nouns.length && i < adjectives.length; i++) {
            System.out.println(adjectives[i] + " " + nouns[i]);
        }
    }

    public static void shuffle(String[] list, int swapCount) {
        Random random = new Random();
        for(int i = 0; i < swapCount; i++) {
            int index1 = random.nextInt(list.length);
            int index2 = random.nextInt(list.length);

            //Swap these two with each other
            String temp = list[index1];
            list[index1] = list[index2];
            list[index2] = temp;
        }
    }
}

Output in successive runs 连续运行输出

lovely tulips
gorgeous roses
red grass

lovely grass
gorgeous tulips
green roses

lovely tulips
red roses
green grass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM