【发布时间】:2017-05-14 22:57:26
【问题描述】:
我正在尝试为一个项目随机从数组中拉出一个对象,但我必须使用 Math.Random 并且我不确定如何使用。使用 java.util.random 和 nextInt 可以很好地完成这项工作,但我不能使用它们。 我已经看到过有关 math.random 此类问题的其他答案,但其中大多数是用于从数组中提取随机对象的索引,而不是对象本身。
这是我的课: (现在我在循环中有 random 和 nextInt 只是为了展示它应该如何工作,但我需要从 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;
}
}
}
【问题讨论】:
-
这里的具体问题是什么?
-
为什么要这样做?
Random和nextInt是正确使用的东西。