How to generate a Random Number between 1 and 10 in Java
Table of Contents
Randomness is useful in programming for many things.
You can use randomness in programming to simulate dice rolls, lottery tickets, and other random events.
In this post, we will learn how to generate random numbers between 1 and 10 in Java.
Using Random Instance
The recommended way to use random is to create a new instance of the Random
class, and then use the instance to generate random numbers.
This class is built-in to Java, so you don't need to use a third-party library to use it.
Simply import the package and use the nextInt
method:
JAVAimport java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
int min = 1;
int max = 10;
int value = random.nextInt(max + min) + min;
System.out.println(value);
}
}
BASH5
The parameter of the nextInt
method is the maximum value that can be generated, and it includes 0. Because we don't actually want 0
to ever be generated if we want numbers between 1 and 10, we need to add 1 to the result, in our case, min
.
Using Math class
Another way to generate random numbers is to use the Math
class.
This class contains a random()
method that returns a random float between 0 and 1.
This is useful because we just need to do a simple multiplication to get a random number between 1 and 10.
Here's an example:
JAVApublic class Main {
public static void main(String[] args) {
Random random = new Random();
int min = 1;
int max = 10;
int value = (int) (Math.random() * (max - min)) + min;
System.out.println(value);
}
}
BASH6
We have to cast it to an int
because the Math.random()
method returns a float, even though we want an int
.
Conclusion
In this post, we learned how to generate random numbers between 1 and 10 in Java using the Random
class and the Math
class.
Either way works, it just depends on how you want to use it or what kind of data type you want in return.
Hopefully, you found this post interesting and useful. Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Getting Started with Deno
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Setting Up a Local Web Server using Node.js