Jarvus The CSCI Retardus Jarvus The CSCI Retardus - 1 year ago 55
Java Question

Random sentence generator returning numbers and not sentence

I am suppose to create a random sentence generator. I have done everything but when I run a test, instead of returning a sentence it returns a number.

If it should return "A beautiful car explodes.", returns 0100. instead.

I am pretty sure I am missing something but at this point I cannot figure it out. I believe my test is written wrong, but I am not sure. Any help would be appreciated. Thank you!

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;

Answer Source

You're returning numbers, not the element of the array at the number. To return the element of an array at a certain index, you'll use the syntax

arrayElementAtIndex = arrayName[arrayIndex];

Also, you need to include spaces in your strings to make spaces. Change your second to last line to

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

As long as your indexes are correct, it'll work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download