Hi am trying to create a random sentence generator for my Java Class the only issue is it builds successfully and rans fine but the output is not what is expected of the program. It should randomly generate 20 sentences.

Here is my code

// Exercise 16.5 : Sentences.java
// Application randomly generates sentences.
import java.util.Random;

public class SentencesNew1
{
   public static void main( String args[])
   {
      Random generator = new Random();

       String article[] = { "the ", "a ", "one ", "some ", "any " };
	  // define noun, verb, preposition in same way here
       String noun[]={"boy","dog","car","bicycle"};
       String verb[]={"ran","jumped","sang","moves"};
       String preposition[]={"away","towards","around","near"};


      // randomly create sentence
      for ( int j = 0; j < 20; j++ )
      {
         int article1 = generator.nextInt( article.length );
         // generat others here like noun1, verb1, ....
          int noun1 = generator.nextInt( article.length );
          int verb1 = generator.nextInt( article.length );
          int preposition1 =generator.nextInt(article.length);
          int article2=generator.nextInt(article.length);
          int noun2=generator.nextInt(article.length);
          
         StringBuilder buffer = new StringBuilder();

         // concatenate words and add period
            buffer.append(article[article1]).append(noun[noun1]).append
                    (verb[verb1]).append(preposition[preposition1]).append
                    (article[article2]).append(noun[noun2]).append( ".\n");

         // capitalize first letter and display
         buffer.setCharAt(
            0, Character.toUpperCase( buffer.charAt( 0 ) ) );
         System.out.println( buffer.toString() );
      } // end for
   } // end main
}  // end class Sentences

Here is my output


run:
The bicyclesangawaysome boy.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
A carjumpedaroundany boy.

at SentencesNew1.main(SentencesNew1.java:32)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

You want to create 20 centances. is there any pre-defined order of the array?
I mean has to code pick one item from 1st array, then one item from 2nd array, one item from 3rd array and one item from 4th array? Or can be custom?

I noticed where my mistake was thanks for the help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.