dimanche 27 octobre 2019

how to generate 3 words using random class

I am given a multi-array (based on page, paragraph, and line number chosen randomly) that tells a story. I need to generate a password containing 3 words taken randomly from the array. Rules have to be given to creating the password (eg: it must be 10 characters long, no repetition of the same word);

This is for Java. I made sure I was using the random class to make sure my 3 words are selected randomly from the array given. I've declared the variables for page, paragraph and line number so that it can pick any single string from array. Then I used split() to separate each word in the random string.

I created an if-else statement for a rule I made to creating a password. If a rule(s) is not followed, the program must always go back to the step where the page, paragraph and line number are chosen randomly, and I have to use random class to generate random numbers using nextInt() method.

 import java.util.Random;

 public class passGen {

   public static void main(String[] args) {

   Random r=new Random();

int pageNum = r.nextInt(story.length);
    int paraNum = r.nextInt(story.length);
    int lineNum = r.nextInt(story.length);

    System.out.print("Password = ");

    for (int i = 0; i<3; i++) {

        String sentence = story[pageNum][paraNum][lineNum]; // story is the array given
        String[] string = sentence.split(" ");  
        int index = new Random().nextInt(string.length);            
        String randomWord = string[index];

        if (randomWord.equals("a") || randomWord.contains("\n")) {
        }
        else 
            System.out.print(randomWord);

    }
      }
    }

Let's say the random generator picks a random sentence from the array: story[0][1][5] gives "The boy is riding on a bicycle\n". Using split() and then randomly selecting the word based on its index, it picks the random word "bicycle\n". I made a rule that if it picks a word with new line ('\n') it must go back to the step where it generates random numbers again and gives me a new array and finds me a new random word until it finds me a word that doesn't have \n. For example, let's say story[0][1][6] is "He is having fun."

I expected the output to print one password with 3 random words combined all the time.

         password =  boyfun.riding   // fun. is considered as one word with the period.

but there were cases that when it failed, it only prints out words that passed the restriction ('\n'). Sometimes it would print 1 word, or 2 words, or it will give an error when I run the program.

password = ridingfun

password = boy 

Password = Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Assign3Q1.main(passGen.java:123)

// line 123 happens is the String sentence = story[pageNum][paraNum][lineNum];



Aucun commentaire:

Enregistrer un commentaire