使用StringBuilder创建随机词-P

时间:2018-07-09 11:33:25

标签: p

我正在尝试使用字符串生成器和随机数创建10行3个单词的行。目前,我有两个循环,但没有产生我想要的。

 public String generateRandSentences() {

        }
    }
    return strBuilder.toString();
}

3 个答案:

答案 0 :(得分:1)

尝试逐步进行操作,您可以替换这些行

String rGenCharSet = sentences[rGen.nextInt(sentences.length)];
            strBuilder.append(rGenCharSet + " ");

int randomnumber =  rGen.nextInt(sentences.length);
String rGenCharSet = sentences[randomnumber];
strBuilder.append(rGenCharSet + " ");

,然后尝试在输出中打印字符串生成器

请注意,println()打印一个字符串生成器,如下所示:

System.out.println(sb);

因为sb.toString()被隐式调用,就像println()调用中的任何其他对象一样。

答案 1 :(得分:0)

因为从未插入行分隔符,所以它会生成一行包含75个字符的行。尝试在每个句子生成后添加strBuilder.append('\n'),如下所示:

public String generateRandSentences() {
    String[] sentences = {"mum", "can", "you", "get", "one", "bun", "for",
            "guy", "one", "for", "gus", "his", "old", "man", "who"};
    StringBuilder strBuilder = new StringBuilder();
    Random rGen = new Random();

        for (int row = 0; row < 5; row++) {
            for (int words = 0; words < 15; words++) {
            String rGenCharSet = sentences[rGen.nextInt(sentences.length)];
            strBuilder.append(rGenCharSet + " ");
        }
        strBuilder.append('\n');
    }
    return strBuilder.toString();
}

TextView txtView1 = findViewById(R.id.txtview_vc_1);
txtView1.setText(generateRandSentences());

答案 2 :(得分:0)

import java.util.*;

class Main {
 public static void main(String[] args){

generateRandSentences();

                                    }




public static void generateRandSentences() {
Random rGen = new Random();
String[] sentences = {"mum", "can", "you", "get", "one", "bun", "for","guy", "one", "for", "gus", "his", "old", "man", "who"};
int size = sentences.length;
for(int i = 0 ; i < 5 ; i++)
{
  StringBuilder strBuilder = new StringBuilder();
  for(int j = 0 ; j < 15 ; j++)
  {
    String str = sentences[rGen.nextInt(size)];
    strBuilder.append(str + " ");
  }
  System.out.println(strBuilder.toString());  
}


                                            }
      }