So im trying to learn Java, and I have written this code that is supposes to generate combinations of words from lists, and then placed in a sentence. The problem is that the random selected word (name) from the first list which contains only names, will be reused ( I know why but Im not sure if I need a "phrase3" or a third list.
Here is my code:
package ListOfWords;
public class test {
public static void main (String[] args) {
String[] name = {"Nicole","Ronnie","Robbie","Alex","Deb"};
String[] action = {"liar","driver","cook","speller","sleeper","cleaner","soccer
player"};
// find out how many words there are in each list
int nameLength = name.length;
int actionLength = action.length;
// Generate two random numbers
int rand1 = (int) (Math.random() * nameLength);
int rand2 = (int) (Math.random() * actionLength);
String phrase1 = name[rand1];
String phrase2 = action[rand2];
System.out.print("It is obvious that" + ' ' + phrase1 + " " + "is a better" + " " +
phrase2 + " " + "than" + " " + phrase1 + "!" );
}
}
this is the result I get at the moment:
It is obvious that Robbie is a better cleaner than Robbie!
so as you see the random name from the first list gets reused - how can I make sure that it will not pick the same element(name) from the first list?
You need a third random number and phrase, to select the second name to be used. For example:
// Generate two random numbers
int rand1 = (int) (Math.random() * nameLength);
int rand2 = (int) (Math.random() * actionLength);
int rand3 = (int) (Math.random() * nameLength);
String phrase1 = name[rand1];
String phrase2 = action[rand2];
String phrase3 = name[rand3];
System.out.print("It is obvious that" + ' ' + phrase1 + " " + "is a better" + " " +
phrase2 + " " + "than" + " " + phrase3 + "!" );
Edit: To avoid the possibility of having the same name selected for both phrase1 and phrase3, the following code should ensure that a different index is used for selecting phrase3 than phrase1:
int rand1 = (int) (Math.random() * nameLength);
int rand2 = (int) (Math.random() * actionLength);
int rand3 = (int) (Math.random() * nameLength);
while(rand1==rand3){
rand3 = (int) (Math.random() * nameLength);
}
This will cause rand3 to be changed until it is not the same as rand1, which will select different names for phrase1 and phrase3.
Note that if the names array only has one name in it, this will cause an infinite loop.
You can do it like this:
List<String> randomNames = new ArrayList(Arrays.asList(name));
Collections.shuffle(randomNames);
int randAction = (int) (Math.random() * actionLength);
String phrase1 = randomNames.get(0);
String phrase2 = action[randAction];
String phrase3 = randomNames.get(1);
System.out.print("It is obvious that " + phrase1 + " is a better "
+ phrase2 + " than " + phrase3 + "!" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With