I'm trying to pull an object out of an array at random for a project, but I have to use Math.Random and I'm not sure how. Using java.util.random and nextInt do the job beautifully, but I can't use them. I've seen other answers to this type of problem with math.random, but most of them are for pulling the index of the random object from the array, not the object itself.
Here is my class: (Right now I have random and nextInt in the loop just to show how it should work, but I'll need to get the exact same result from Math.random)
import java.util.Scanner;
import java.util.Random;
public class Madlibsdriver
{
static Scanner scan= new Scanner (System.in);
public static void main(String[] args)
{
System.out.print ("Welcome to Mad libs!");
System.out.println();
System.out.println("----------------------------------------------");
System.out.println("Enter a noun:");
String ip1= scan.nextLine();
System.out.println("Enter an adjective:");
String ip2= scan.nextLine();
System.out.println ("Enter a verb:");
String ip3= scan.nextLine();
System.out.println ("Enter an adverb (ex: angrily) :");
String ip4= scan.nextLine();
System.out.println ("Enter another noun:");
String ip5= scan.nextLine();
Phrase obama= new Obama(ip1, ip2, ip3, ip4, ip5);
Phrase shake= new Shakespeare (ip1, ip2, ip3, ip4, ip5);
Phrase horror= new Horror (ip1, ip2, ip3, ip4, ip5);
Phrase mystery= new Mystery (ip1, ip2, ip3, ip4, ip5);
Phrase romance= new Romance (ip1, ip2, ip3, ip4, ip5);
Phrase[]libs= new Phrase [5];
libs[0]= obama;
libs[1]= shake;
libs[2]= hooror;
libs[3]= mystery;
libs[4]= romance;
System.out.println("Press 1 to generate a mad lib or 2 to exit.");
int begin= scan.nextInt();
while ((ip1.length()>0)&& begin==1)
{
Random rand = new Random();
System.out.println();
System.out.println ( libs[rand.nextInt(libs.length)]);
System.out.println("---------------------------------------");
System.out.print ("To play again, press 1. To exit, press 2.");
begin=scan.nextInt();
if (begin==2) break;
}
}
}
Aucun commentaire:
Enregistrer un commentaire