java - 随机句子生成器返回数字而不是句子

标签 java arrays string random

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

示例: 如果它应该返回“A beautiful car explodes.”,则返回 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;

最佳答案

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

arrayElementAtIndex = arrayName[arrayIndex];

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

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

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

关于java - 随机句子生成器返回数字而不是句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39517768/

相关文章:

java - android 内部结构和内存/处理器限制?

java - ZonedDateTime 的 Jackson 反序列化问题

java - 是否可以为不是从我的代码启动的进程创建 java.lang.Process 实例?

c - 相同的表达式,但在函数中使用时返回值不同

c - 从函数返回一个值

python - 比较两个 Pandas 系列中的字符串条目

java - 我确信一定有一种更简单的 java arraylist 求和方法

javascript - 重命名数组中多个相同的匹配项

python - 为什么python同时使用 ""和 ' '来制作字符串文字

Ruby:将字符串中的所有整数递增+1