-1

我的以下代码是这样工作的:

import java.util.Scanner;
import java.lang.Math;
public class Magiceightball {
private static void Number() {
    int magic = (int) Math.ceil(Math.random() * 10);
    String x;
    switch (magic)
    {
        case 1: x = "Yes.";
        break;
        case 2: x = "No.";
        break;
        case 3: x = "The odds are in favor.";
        break;
        case 4: x = "The odds are against you.";
        break;
        case 5: x = "Never.";
        break;
        case 6: x = "Definitely!";
        break;
        case 7: x = "Maybe.";
        break;
        case 8: x = "I don't think so.";
        break;
        case 9: x = "I'd say no.";
        break;
        case 10: x = "Probably.";
        break;

        default: x = "Try Again.";
        break;
    }
    System.out.println(x);
}

public static void main (String [ ] args)
{
    Scanner scan = new Scanner(System.in);

    boolean a = true;

    while (a)
    {
        System.out.println();
        System.out.println();
        System.out.println("What would you like to ask the Magic Eight Ball? Make it a \"Yes\" or \"No\" question for it to work.");
        System.out.print("\n\n--> ");
        String what = scan.nextLine();
        System.out.println();
        Number();

        System.out.println();
        System.out.println();            
        System.out.println();
        System.out.println("Would you like to go again? Enter \"Y\" for yes, and \"N\" for no.");

        System.out.print("\n\n--> ");
        String run = scan.nextLine();
        run = run.toLowerCase();

        if (run.equals("n"))
        {
            a = false;
        }
    }
}

} `

我的困境是,我希望所有这些方法都用于 switch 语句、while 循环,但我想用 SecureRandom 方法替换 Math.random 我将如何去做呢?

我尝试使用整个 SecureRandom randomNumber = new SecureRandom(); 这样做,但它一直给我错误,我无法将安全随机转换为“int”。

4

2 回答 2

1

您可以使用此功能:

public static int generateRandomInteger(int min, int max) {
    SecureRandom rand = new SecureRandom();
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}

调用它

int magic = generateRandomInteger(1,10); // to get a number between 1 and 10.
于 2017-10-27T16:53:25.877 回答
1

你只需要实例化一个SecureRandom对象并使用它的nextInt()方法:

Random rand = new SecureRandom();
int magic = 1 + rand.nextInt(10);
于 2017-10-27T16:50:12.287 回答