所以我的代码如下:
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”。
答案 0 :(得分:0)
您只需要实例化SecureRandom
对象并使用其nextInt()
方法:
Random rand = new SecureRandom();
int magic = 1 + rand.nextInt(10);
答案 1 :(得分:0)
您可以使用此功能:
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.