Home > database >  Separate "for" loop iterations
Separate "for" loop iterations

Time:02-07

How would I go about making each iteration of my four loop be random. The outcome as of now makes all 20 sentences put the same output, although it is choosing random words each time from the four arrays created in static class OuterWord. I have omitted the parts of the code that I don't think are necessary including the getMethods created for each array and sentence, hopefully that will not negatively effect my question.

`public class SentenceMaker {

static class OuterWord {
    //arrays
    String [] article = {"the", "a", "one", "some", "any"}; //array for articles
    String [] noun = {"boy", "girl", "dog", "town", "car"}; //array for nouns
    String [] verb = {"drove", "jumped", "ran", "walked", "skipped"}; //array for verbs
    String [] preposition = {"to", "from", "over", "under", "on"}; //array for prepositions

}
static class OuterSentence {
   int random = (int) (Math.random()*5);
    OuterWord word = new OuterWord();

    //sentence structure article-noun-verb-preposition-article-noun
    //StringBuilder with append, attempts to concatenate with .append
    //This code works as well
    StringBuilder sentence = new StringBuilder()
                    .append(word.article[random].substring(0, 1).toUpperCase())
                    .append(word.article[random].substring(1))
                    .append(" ")
                    .append(word.noun[random])
                    .append(" ")
                    .append(word.verb[random])
                    .append(" ")
                    .append(word.preposition[random])
                    .append(" ")
                    .append(word.article[random])
                    .append(" ")
                    .append(word.noun[random])
                    .append(".");
}


public static void main(String args[]) {
    //random element from arrays
    //int random = (int) (Math.random()*5);

    //instantiation of the Word and Sentence classes
    OuterWord word = new OuterWord();
    OuterSentence s = new OuterSentence();


    //loop initializer
    int counter = 0;

    //for loop for 20 iterations
    for(int i = 0; i < 20; i  ){
        //counter to keep track of iterations
        counter = counter   1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence "   counter   ": "   s.sentence.);
    }
}

}`

CodePudding user response:

I would start by moving everything into a single class, your code is needlessly complicated by the way you have organized it.

private static String[] article = { "the", "a", "one", "some", "any" };
private static String[] noun = { "boy", "girl", "dog", "town", "car" };
private static String[] verb = { "drove", "jumped", "ran", "walked", "skipped" };
private static String[] preposition = { "to", "from", "over", "under", "on" };

Next, I would write a method to get the title case of a given word. You only need to capitalize the first character, but a StringBuilder is great for that.

private static String getTitleCase(String w) {
    StringBuilder sb = new StringBuilder(w);
    sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
    return sb.toString();
}

Then building a sentence, I would move that to a method. You currently only get a single random index and build a single sentence. Instead, get a random value appropriate to each array length and I would use a StringJoiner to simplify adding the spaces between words. Like,

private static String buildSentence() {
    Random rand = ThreadLocalRandom.current();
    StringJoiner sj = new StringJoiner(" ");
    sj.add(getTitleCase(article[rand.nextInt(article.length)]));
    sj.add(noun[rand.nextInt(noun.length)]);
    sj.add(verb[rand.nextInt(verb.length)]);
    sj.add(preposition[rand.nextInt(preposition.length)]);
    sj.add(article[rand.nextInt(article.length)]);
    sj.add(noun[rand.nextInt(noun.length)]);
    return String.format("%s.", sj);
}

Finally, call the above method twenty times

public static void main(String[] args) {
    for (int i = 0; i < 20; i  ) {
        System.out.println(buildSentence());
    }
}

CodePudding user response:

Just move the OuterSentence object to for loop.

for(int i = 0; i < 20; i  ){
        OuterSentence s = new OuterSentence();
        //counter to keep track of iterations
        counter = counter   1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence "   counter   ": "   s.sentence);
    }

The above one is much readable or the other way is to just create the new object in the System.out.println statement like as follows:

System.out.println("Sentence "   counter   ": "   new OuterSentence().sentence);

In both the ways we are creating a new object for every statement so that new random will get generated so that new sentence will be formed.

CodePudding user response:

Change

System.out.println("Sentence "   counter   ": "   s.sentence.);

to

System.out.println("Sentence "   counter   ": "   new OuterSentence().sentence);

Problem: I haven't gone through your code line by line but from my understanding - You have created a random object of OuterSentence() and now are calling that single random object 20 times in a loop.

  •  Tags:  
  • Related