Table of Contents
1. Understand randomness and random number generation
2. Store and count random numbers
2.1 Store random numbers
3. Results analysis and extension functions
3.1 Report the number of occurrences of each number
3.2 Find the number that appears the most
3.3 Analyze the frequency of odd and even numbers (simulate the front and back of the coin)
4. Complete sample code
5. Precautions and summary
Home Java javaTutorial Java random integer generation and frequency statistics: simulation experiments and result analysis

Java random integer generation and frequency statistics: simulation experiments and result analysis

Aug 30, 2025 am 10:12 AM

Java random integer generation and frequency statistics: simulation experiments and result analysis

This article aims to guide readers how to use Java to generate random integers within a specified range and perform frequency statistics and analysis of these random numbers. We will explore the characteristics of random numbers, how to implement a general method of generating random numbers and counting occurrences, and further analyze the most common numbers and the distribution of odd and even numbers, and finally provide a complete example code to help readers understand and apply these concepts.

1. Understand randomness and random number generation

In programming, generating random numbers is a common requirement, such as simulated throwing coins, rolling dices, etc. However, the understanding of "random" can sometimes lead to misunderstandings. True randomness means that the probability of each result appearing is independent, and in small sample sizes, the distribution of the results may appear uneven, and even continuous identical results appear. For example, it is possible to throw a coin 10 times in a row, 5 front and 5 reverses, but 8 front and 2 reverses are also completely random. Only under large sample sizes can the distribution of the results approach a theoretically uniform distribution.

Java provides the Math.random() method to generate a double type random number in the range [0.0, 1.0). To generate integers within the specified range [a, b], you can use the following formula:

 (int) (Math.random() * (b - a 1) a)

For example, generate a random integer between 1 and 10:

 int randomNumber = (int) (Math.random() * 10 1); // Generate an integer of [1, 10]

To better encapsulate this logic, we can create a common method:

 /**
 * Generates a random integer (including min and max) within the specified range [min, max].
 * @param min minimum value * @param max maximum value * @return Random integers in range */
public static int generateRandomInteger(int min, int max) {
    return (int) (Math.random() * (max - min 1) min);
}

2. Store and count random numbers

After a series of random numbers are generated, they are usually stored and the frequency of occurrence of each number is counted.

2.1 Store random numbers

We can use an int array or List to store the generated random numbers. ArrayList is a better choice if flexible capacity is required.

 import java.util.ArrayList;
import java.util.List;

// ... int numberOfFlips = 1000 in the main method or elsewhere; // Number of simulations List<integer> results = new ArrayList(numberOfFlips);
for (int i = 0; i <h4> 2.2 Number of statistics occurrences</h4>
<p> There are several ways to count the occurrence of each number:</p>
<ul>
<li> <strong>Use arrays:</strong> If the range of random numbers is fixed and small, you can directly use an array as the frequency counter. The index of the array corresponds to a random number, and the value of the array stores the number of occurrences.</li>
<li> <strong>Use HashMap:</strong> For any range of random numbers or uncertain ranges of random numbers, HashMap<integer integer> is a more flexible choice, the key is a random number and the value is an occurrence.</integer>
</li>
</ul>
<p> Here we take HashMap as an example because it is more general.</p>
<pre class="brush:php;toolbar:false"> import java.util.HashMap;
import java.util.Map;

/**
 * Statistics the number of occurrences of each number in the list.
 * @param numbers List of random numbers* @return A Map, the key is a number, and the value is its occurrence number*/
public static Map<integer integer> countOccurrences(List<integer> numbers) {
    Map<integer integer> occurs = new HashMap();
    for (int num : numbers) {
        occurrences.put(num, occurrences.getOrDefault(num, 0) 1);
    }
    return occurrences;
}</integer></integer></integer>

If you need to count the number of occurrences of a specific value n in a given array arr, you can implement an auxiliary method:

 /**
 * Statistics the number of occurrences of the specified value n in the given array arr.
 * @param n Value to count* @param arr Integer array* @return Number of times value n appears in the array*/
public static int countValueInArray(int n, int[] arr) {
    int count = 0;
    for (int value : arr) {
        if (value == n) {
            count ;
        }
    }
    return count;
}

Note: In actual applications, if you already have frequency statistics in the form of Map, it will be more efficient to directly obtain a number from the Map than to traverse the entire original array. The countValueInArray method is suitable for scenarios where a single query is required to be performed on the original array.

3. Results analysis and extension functions

After counting the occurrence of each number, we can further analyze these data to meet specific needs.

3.1 Report the number of occurrences of each number

By traversing the statistical results Map, you can print the number of occurrences of each number.

 public static void printOccurrences(Map<integer integer> occurrences) {
    System.out.println("--- The frequency of digital occurrence----");
    for (Map.Entry<integer integer> entry : occurences.entrySet()) {
        System.out.println(entry.getKey() ": " entry.getValue() " times");
    }
}</integer></integer>

3.2 Find the number that appears the most

Traversing the statistical result Map, recording the number with the most occurrences and the number of times.

 public static void findMostFrequentNumber(Map<integer integer> occurs) {
    int mostFrequentNum = -1;
    int maxCount = -1;

    for (Map.Entry<integer integer> entry : occurences.entrySet()) {
        if (entry.getValue() > maxCount) {
            maxCount = entry.getValue();
            mostFrequentNum = entry.getKey();
        }
    }
    if (mostFrequentNum != -1) {
        System.out.println("The number with the most occurrences is: " mostFrequentNum " (" maxCount " times)");
    } else {
        System.out.println("No number was counted.");
    }
}</integer></integer>

3.3 Analyze the frequency of odd and even numbers (simulate the front and back of the coin)

If we treat even numbers as "positive" and odd numbers as "negative", we can count their occurrences separately.

 public static void analyzeEvenOddOccurrences(Map<integer integer> occurrences) {
    int evenCount = 0;
    int oddCount = 0;

    for (Map.Entry<integer integer> entry : occurences.entrySet()) {
        if (entry.getKey() % 2 == 0) {
            evenCount = entry.getValue();
        } else {
            oddCount = entry.getValue();
        }
    }

    System.out.println("--- Odd and even statistics---");
    System.out.println("even number (front) occurrences: " evenCount " times");
    System.out.println("oddCount (reverse) Number of occurrences: " oddCount " times");

    if (evenCount > oddCount) {
        System.out.println("even (front) appears more times.");
    } else if (oddCount > evenCount) {
        System.out.println("Odd number (reverse) appears more times.");
    } else {
        System.out.println("Odd and even numbers appear the same number of times.");
    }
}</integer></integer>

4. Complete sample code

Integrate all the above functions into a complete Java program, simulate the number of throws entered by the user and conduct a comprehensive statistical analysis.

 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class RandomNumberAnalysis {

    // 1. Create and use a method to generate a random integer within the specified range [a, b] public static int generateRandomInteger(int min, int max) {
        return (int) (Math.random() * (max - min 1) min);
    }

    // 2. Create and use a method to count the number of occurrences of a specific value n in a given array arr // Here, in order to adapt to List<integer>, we use List as the parameter public static int countValueInList(int n, List<integer> list) {
        int count = 0;
        for (int value : list) {
            if (value == n) {
                count ;
            }
        }
        return count;
    }

    /**
     * Statistics the number of occurrences of each number in the list.
     * @param numbers List of random numbers* @return A Map, the key is a number, and the value is its occurrence number*/
    public static Map<integer integer> countAllOccurrences(List<integer> numbers) {
        Map<integer integer> occurs = new HashMap();
        for (int num : numbers) {
            occurrences.put(num, occurrences.getOrDefault(num, 0) 1);
        }
        return occurrences;
    }

    /**
     * Print the frequency of occurrence of each number.
     * @param occurrences Map containing numbers and their occurrences
     * @param minNum Minimum value of the range of random numbers* @param maxNum Maximum value of the range of random numbers*/
    public static void printAllOccurrences(Map<integer integer> occurrences, int minNum, int maxNum) {
        System.out.println("\n--- The frequency of occurrence of each number---");
        for (int i = minNum; i  occurs) {
        int mostFrequentNum = -1;
        int maxCount = -1;

        for (Map.Entry<integer integer> entry : occurences.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                mostFrequentNum = entry.getKey();
            }
        }
        if (mostFrequentNum != -1) {
            System.out.println("\nThe number with the most occurrences is: " mostFrequentNum " (" maxCount " times)");
        } else {
            System.out.println("\nNo number was counted.");
        }
    }

    /**
     * Analyze the frequency of odd and even numbers.
     * @param occurrences Map containing numbers and their occurrences
     */
    public static void analyzeEvenOddOccurrences(Map<integer integer> occurrences) {
        int evenCount = 0;
        int oddCount = 0;

        for (Map.Entry<integer integer> entry : occurences.entrySet()) {
            if (entry.getKey() % 2 == 0) {
                evenCount = entry.getValue();
            } else {
                oddCount = entry.getValue();
            }
        }

        System.out.println("\n--- Odd and even statistics (even number = front, odd number = reverse) ---");
        System.out.println("even number (front) occurrences: " evenCount " times");
        System.out.println("oddCount (reverse) Number of occurrences: " oddCount " times");

        if (evenCount > oddCount) {
            System.out.println("Conclusion: Even (positive) appears more times.");
        } else if (oddCount > evenCount) {
            System.out.println("Conclusion: Odd number (reverse) appears more times.");
        } else {
            System.out.println("Conclusion: Odd and even numbers appear the same number of times.");
        }
    }

    public static void main(String[] args) {
        try (Scanner inputReader = new Scanner(System.in)) {
            System.out.print("Please enter the number of throws you want to simulate (for example, 1000): ");
            int amount = inputReader.nextInt();

            if (amount  generatedNumbers = new ArrayList(amount);
            for (int i = 0; i  occurrencesMap = countAllOccurrences(generatedNumbers);
            printAllOccurrences(occurrencesMap, MIN_RANDOM, MAX_RANDOM);

            // 2. Find the number with the most occurrences findMostFrequentNumber(occurrencesMap);

            // 3. Analyze the occurrence frequency of odd and even numbers analyzeEvenOddOccurrences(occurrencesMap);

            // Example: Use countValueInList method to count the occurrence of a specific number System.out.println("\n--- Single numeric statistics example---");
            int specificNumber = 5;
            System.out.println("number" specificNumber " appears" countValueInList(specificNumber, generatedNumbers) " times.");

        } catch (Exception e) {
            System.err.println("Error occurred: " e.getMessage());
        }
    }
}</integer></integer></integer></integer></integer></integer></integer></integer></integer>

5. Precautions and summary

  • Random understanding: Even if it is “random”, small sample sizes may have uneven distribution. This is an inherent feature of random numbers, not a program error. As the number of simulations (sample size) increases, the results will become closer to the theoretical uniform distribution.
  • java.util.Random: Math.random() uses the default instance of java.util.Random internally. If better randomness control is needed (for example, using specific seeds to generate reproducible random sequences), you can create a java.util.Random object directly.
     import java.util.Random;
    // ...
    Random rand = new Random(); // or new Random(seed)
    int randomNumber = rand.nextInt(max - min 1) min; // Generate an integer of [min, max]
  • Debugging skills: When the program behavior does not meet expectations, learning to use System.out.println() to output variable values ​​at key points, or using the IDE's debugger (set breakpoints, step by step, view variables) to track program execution process and data changes, which is an effective means to locate problems.

Through the study of this article, you should have mastered the method of generating random integers within a specified range in Java and conducting comprehensive statistics and analysis of these random numbers. These skills are very practical in simulation, game development, data analysis and other fields.

The above is the detailed content of Java random integer generation and frequency statistics: simulation experiments and result analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

How to join an array of strings in Java? How to join an array of strings in Java? Aug 04, 2025 pm 12:55 PM

Using String.join() (Java8) is the easiest recommended method for connecting string arrays, just specify the separator directly; 2. For old versions of Java or when more control is needed, you can use StringBuilder to manually traverse and splice; 3. StringJoiner is suitable for scenarios that require more flexible formats such as prefixes and suffixes; 4. Using Arrays.stream() combined with Collectors.joining() is suitable for filtering or converting the array before joining; To sum up, if Java8 and above is used, the String.join() method should be preferred in most cases, which is concise and easy to read, but for complex logic, it is recommended.

How to implement a simple TCP client in Java? How to implement a simple TCP client in Java? Aug 08, 2025 pm 03:56 PM

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

How to compare two strings in Java? How to compare two strings in Java? Aug 04, 2025 am 11:03 AM

Use the .equals() method to compare string content, because == only compare object references rather than content; 1. Use .equals() to compare string values equally; 2. Use .equalsIgnoreCase() to compare case ignoring; 3. Use .compareTo() to compare strings in dictionary order, returning 0, negative or positive numbers; 4. Use .compareToIgnoreCase() to compare case ignoring; 5. Use Objects.equals() or safe call method to process null strings to avoid null pointer exceptions. In short, you should avoid using == for string content comparisons unless it is explicitly necessary to check whether the object is in phase.

How to send and receive messages over a WebSocket in Java How to send and receive messages over a WebSocket in Java Aug 16, 2025 am 10:36 AM

Create a WebSocket server endpoint to define the path using @ServerEndpoint, and handle connections, message reception, closing and errors through @OnOpen, @OnMessage, @OnClose and @OnError; 2. Ensure that javax.websocket-api dependencies are introduced during deployment and automatically registered by the container; 3. The Java client obtains WebSocketContainer through the ContainerProvider, calls connectToServer to connect to the server, and receives messages using @ClientEndpoint annotation class; 4. Use the Session getBasicRe

Correct posture for handling non-UTF-8 request encoding in Spring Boot application Correct posture for handling non-UTF-8 request encoding in Spring Boot application Aug 15, 2025 pm 12:30 PM

This article discusses the mechanism and common misunderstandings of Spring Boot applications for handling non-UTF-8 request encoding. The core lies in understanding the importance of the charset parameter in the HTTP Content-Type header, as well as the default character set processing flow of Spring Boot. By analyzing the garbled code caused by wrong testing methods, the article guides readers how to correctly simulate and test requests for different encodings, and explains that Spring Boot usually does not require complex configurations to achieve compatibility under the premise that the client correctly declares encoding.

Exploring Common Java Design Patterns with Examples Exploring Common Java Design Patterns with Examples Aug 17, 2025 am 11:54 AM

The Java design pattern is a reusable solution to common software design problems. 1. The Singleton mode ensures that there is only one instance of a class, which is suitable for database connection pooling or configuration management; 2. The Factory mode decouples object creation, and objects such as payment methods are generated through factory classes; 3. The Observer mode automatically notifies dependent objects, suitable for event-driven systems such as weather updates; 4. The dynamic switching algorithm of Strategy mode such as sorting strategies improves code flexibility. These patterns improve code maintainability and scalability but should avoid overuse.

See all articles