javarandomwhile-loopswitch-statementsecure-random

Magic 8ball Using securerandom with switch statements and while loops


I have my following code working like this:

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;
        }
    }
}

} `

My dilemma is, I want all these methods being used the switch statement, the while loop but I want to replace the Math.random with the SecureRandom method how would I go about doing that?

I tried using the whole SecureRandom randomNumber = new SecureRandom(); to do it but it kept giving me errors that I could not convert secure random to "int".


Solution

  • You just need to instantiate a SecureRandom object and use its nextInt() method:

    Random rand = new SecureRandom();
    int magic = 1 + rand.nextInt(10);