如何用随机数计算周长?

How to calculate circumference with random numbers?

我需要用 Math.random() * Math.Pi; 打印圆周,但我做错了什么或遗漏了什么。每个随机生成的数字等于圆的半径。我的想法是在 getRandomNumberInRange method 中计算 Pi,但是当我这样做时,出现错误:

Bad operand for type double

import java.util.Random;
import java.util.Scanner;

    final static double PI = 3.141592564;
    static Scanner sc = new Scanner(System.in);

        public static void main(String[] args) {

    //ask the player to enter a number less than or equal to 18 and higher to 9.

                            System.out.println(" Please enter a number less than or equal to 18 and above 9: ");
                            int random = sc.nextInt ();

                            //send error message if bad input
                              if (random < 9 || random > 18) {
                System.out.println(" Error. Unauthorized entry . You need to enter a number less than or equal to 18 and above 9 ");
            } else

                          //If the answer is yes , generate nine different random numbers from 0.
                            for (int i = 0; i < 9; i++) {

                                    double surface = PI * (random * 2);

                System.out.println(getRandomNumberInRange(9, 18) + " : " + " The circumference is : " + surface );
            }}

调用的方法:

private static int getRandomNumberInRange(int min, int max) {

        Random r = new Random();

                return r.nextInt((max - min) + 1) + min;
    }

您在 for 循环中调用了 getRandomNumberInRange(),但没有将它分配给任何东西,也没有使用它。 这可能更接近你想要的:

        for (int i = 0; i < 9; i++) {
            int r2 = getRandomNumberInRange(9, 18);
            double surface = PI * (r2 * 2);

            System.out.println(r2 + " : " + " The circumference is : " + surface);
        }