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!
- Getting Started with TypeScript
- Getting Started with Solid
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Getting Started with Vuex: Managing State in Vue