如何在Java Mad Libs程序中使用随机数发生器?

时间:2016-01-04 02:49:47

标签: java

我试图做疯狂的自由,但我很难弄清楚如何让随机发生器从我创建的数组中选择一个随机动词,名词或形容词,因为他们&#39 ;所有单词,而不是数字......字符串句子也是一样。

import java.util.Scanner;
import java.util.Random;


public class Client {
    public static void main(String [] args){
        Scanner input = new Scanner(System.in);
        Random r = new Random();

        //user will enter 5 nouns
        System.out.println("Enter 5 nouns");
        String[] nouns = { "noun", "noun", "noun", "noun",
            "noun"};
        for (int ncount = 0; ncount < 5; ncount++) {
            System.out.print(nouns[ncount] + ": ");
            nouns[ncount] = input.nextLine();
        }



        //user will enter 5 verbs
        System.out.println("Enter 5 verbs");
        String[] verbs = { "verb", "verb", "verb", "verb",
            "noun"};
        for (int vcount = 0; vcount < 5; vcount++) {
            System.out.print(verbs[vcount] + ": ");
            verbs[vcount] = input.nextLine();
        }


        //users will enter 5 adjectives
        System.out.println("Enter 5 adjectives");
        String[] adjectives = { "adjective", "adjective", "adjective", "adjective",
            "adjective"};
        for (int acount = 0; acount < 5; acount++) {
            System.out.print(adjectives[acount] + ": ");
            adjectives[acount] = input.nextLine();
        }





        String sentence1 = "Longwood" +  r.verbs.length + "the" + r.adjectives.length + r.nouns.length;
        String sentence2 = "The" + noun + "in cafe3" + verb + adjective;
        String sentence3 = "The girls will" + verb + adjective + "dresses to the" + noun; 
        String sentence4 = "Students will" + verb + adjective + "at the" + noun; 
        String sentence5 = "Students get"+ adjective + "when their" + noun + "are" + "by the staff."; 
        String sentence6 = "Recieving a day of" + noun+ verb + "me" + adjective; 
        String sentence7 = "At freshman orientation students" + verb + "about the" + adjective + noun + "on"
        + "the roof"; 
        String sentence8 = "Senior" + noun + "is the place where you can" + verb + adjective +"!"; 
        String sentence9 = "The Longwood Varsity"+ noun + "team" + verb + "Long Island" + adjective + "For 2015!"; 
        String sentence10 = "The teacher of my" + noun +  "class" + verb + adjective; 

1 个答案:

答案 0 :(得分:1)

您可以通过

创建没有任何值的空白数组
String[] array = new String[x]; //x is the size of the array

要选择一个随机单词,您可以使用Random nextInt和数组大小的边界。您获得的随机数将是要使用的单词的索引