Home > Java > javaTutorial > How to Generate Random Numbers Between 1 and 50 in Java?

How to Generate Random Numbers Between 1 and 50 in Java?

Patricia Arquette
Release: 2024-11-08 07:36:01
Original
420 people have browsed it

How to Generate Random Numbers Between 1 and 50 in Java?

Generating Random Numbers in Java with Math.random()

To obtain random values from 1 to 50 using Math.random() in Java, you have two options:

Option 1: Using the java.util.Random Class

This class provides a more robust way to generate random numbers:

<code class="java">import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;</code>
Copy after login

Option 2: Using Math.random() Directly

This method can also be used to generate random numbers within the desired range:

<code class="java">double random = Math.random() * 49 + 1;</code>
Copy after login

Here, Math.random() generates a random number between 0 and 1. By multiplying it by 49, you scale it to the range [0 - 49]. Adding 1 then shifts the range to [1 - 50].

You can also cast the result to an integer for convenience:

<code class="java">int random = (int)(Math.random() * 50 + 1);</code>
Copy after login

The above is the detailed content of How to Generate Random Numbers Between 1 and 50 in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template