从给定数组中随机选择单词以形成句子

时间:2015-12-10 10:40:17

标签: java string

我是java编程的初学者,正在经历Ex。 Deitel& Deitel的16.5(随机句子)和问题要求用从给定的文章,名词,动词和介词中随机选择的单词形成句子,以形成20个句子,其中句子必须按顺序形成:article,名词,动词,准备,文章和名词。 它要求在单词之间放置空格,我不知道该怎么做。此外,我以非常错误的方式连接字符串,因此非常感谢帮助和指导。

import java.util.*;

public class Makeit{
  private static String[] article ={"the","a","one","some","any"};
  private static String[] noun={" boy"," girl"," dog"," town"," car"};
  private static String[] verb={" drove"," jmped"," ran"," walked","    skipped"};
  private static String[] preposition={" to"," from"," over"," under"," on"};


  public static void main(String args[]){
  //order to make a sent: a,n,v,p,a,n

    System.out.println("the sentences picked at random are:");
    //loop to generate 20 sentences
    for(int i=0;i<=19;i++){
      System.out.println(makeSentence());   
    }   
  }

  public static String makeSentence(){
    Random rand = new Random();
    int[] index = new int[6];
    String sent = new String();

    for(int i=0;i<6;i++){
         index[i]= rand.nextInt(5);
    }
    sent = sent.concat(article[index[0]].concat(noun[index[1]].concat(verb[index[2]].concat(preposition[index[3]].concat(article[index[4]].concat(noun[index[5]]))))));
    return sent;
  }
}

2 个答案:

答案 0 :(得分:0)

您可以从数组中选取单词并将其存储在变量中:

String article1 = articles[rand.nextInt(articles.length)];
String noun = nouns[rand.nextInt(nouns.length)];
// ...

直接存储这些变量比将索引存储在数组中然后检索元素更好,因为它更有意义:例如index[1]自然显然不是noun数组中用于获取名词的元素的索引;一个名为noun的变量显然是在句子中使用的名词。

然后连接和添加空格非常简单:

sent = article1 + " " + noun + " " + verb + " " + prepo + " " + article2 + " " + noun2;

请注意,无需分配sent = new String():只需将其保留为未初始化,或者将其完全删除并直接返回连接字符串:

return article1 + " " + ...;

答案 1 :(得分:0)

首先,您可以继续使用concat,但在每个单词之间的字符串" "上:

sent.concat(article[index[0]].concat(" ").concat(noun[index[1]].concat(" ").concat(verb[index[2]])));

它变得很麻烦。其次,+时,您可以使用concat运算符代替String

sent = article[index[0]] + " " + noun[index[1]] + " " + verb[index[2]] + " " 
       + preposition[index[3]] + " " + article[index[4]] + " " + noun[index[5]];

此外,您不需要每次在循环中使用Random创建新的Random rand = new Random()。您可以将它移动到循环外的字段或局部变量,并将其传递给您的句子制作方法。

最后,在使用nextInt(5)生成随机数时,您可能需要调用nextInt(noun.length)(或其他数组),以防您在下一个&#34;版本&#34;中更改其大小。