【问题标题】:Random sentence generator returning numbers and not sentence随机句子生成器返回数字而不是句子
【发布时间】:2016-09-15 18:14:53
【问题描述】:

我想创建一个随机句子生成器。我已经做了所有事情,但是当我运行测试时,它不是返回一个句子而是返回一个数字。

示例: 如果它应该返回“一辆漂亮的汽车爆炸了。”,则返回 0100。而不是。

我很确定我错过了一些东西,但此时我无法弄清楚。我相信我的测试写错了,但我不确定。任何帮助,将不胜感激。谢谢!

public class set2{

 public static void main(String[] args) {

    String[] article = new String[4];
    String[] adj = new String[2];
    String[] noun = new String[2];
    String[] verb = new String[3];

    article[0] = "A";
    article[1] = "The";
    article[2] = "One";
    article[3] = "That";

    adj[0] = "hideous";
    adj[1] = "beautiful";

    noun[0] = "car";
    noun[1] = "woman";

    verb[0] = "explodes";
    verb[1] = "is dying";
    verb[2] = "is moving";

    // Test for randomSentence
    System.out.println(randomSentence(article, adj, noun, verb));

  public static String randomSentence(String[] article, String[] adj, String[] noun, String[] verb) {

    Random rand = new Random();

    int articledx = rand.nextInt(article.length);
    int adjdx = rand.nextInt(adj.length);
    int noundx = rand.nextInt(noun.length);
    int verbdx = rand.nextInt(verb.length);

    String sentence = articledx + "" + adjdx + "" + noundx + "" + verbdx + ".";

    return sentence;

【问题讨论】:

标签: java arrays string random


【解决方案1】:

您返回的是数字,而不是数字处的数组元素。要返回某个索引处的数组元素,您将使用语法

arrayElementAtIndex = arrayName[arrayIndex];

此外,您需要在字符串中包含空格以产生空格。 将倒数第二行更改为

String sentence = article[articledx] + " " + adj[adjdx] + " " + noun[noundx] + " " + verb[verbdx] + ".";

只要您的索引正确,它就会起作用。

【讨论】:

    【解决方案2】:

    问题是您正在根据生成的随机 int 构建结果,而不是相应数组中指向的元素...

    修改String sentence

    喜欢:

    String sentence = article[articledx[ + "" + adj[adjdx]+ "" + noun[noundx] + "" + verb[verbdx] + ".";
    

    public static String randomSentence(String[] article, String[] adj, String[] noun, String[] verb) {
        Random rand = new Random();
        int articledx = rand.nextInt(article.length);
        int adjdx = rand.nextInt(adj.length);
        int noundx = rand.nextInt(noun.length);
        int verbdx = rand.nextInt(verb.length);
    
        return  article[articledx[ + "" + adj[adjdx]+ "" + noun[noundx] + "" + verb[verbdx] + ".";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 2011-09-24
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 2016-05-08
      相关资源
      最近更新 更多