【问题标题】:Using math.random (not java.util.random/nextInt) to pull object out of an array?使用 math.random(不是 java.util.random/nextInt)将对象拉出数组?
【发布时间】: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;
}

    }

}

【问题讨论】:

  • 这里的具体问题是什么?
  • 为什么要这样做? RandomnextInt 是正确使用的东西。

标签: java arrays object random


【解决方案1】:

我想你可以使用类似下面的东西。

public static int getRandom(int max) {
  return (int) Math.floor(Math.random() * (max + 1));
}

然后得到一个长度为 n > 0 的数组 arr 的索引:

arr[getRandom(n - 1)]

【讨论】:

    【解决方案2】:

    尝试改变:

    Random rand = new Random();
        System.out.println();
        System.out.println ( libs[rand.nextInt(libs.length)]);
    

    与:

    int length = libs.length;
        double val = length * Math.random();
        System.out.println();
        System.out.println ( libs[(int) val]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-07
      • 2011-08-12
      • 2015-03-20
      • 2013-03-05
      • 2021-07-01
      • 2017-08-08
      • 1970-01-01
      相关资源
      最近更新 更多