Search code examples
javamathrandompi

How to calculate circumference with random numbers?


I need to print the circumference with Math.random() * Math.Pi; but i'm doing something wrong or missing something. Each random generated number equals the radius of the circle. My idea was to calculate Pi in the getRandomNumberInRange method but when I do, I get error:

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

The method called:

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

        Random r = new Random();

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

Solution

  • You call getRandomNumberInRange() in the for loop, but don't assign it to anything, or use it. This is probably closer to what you want:

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