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 Svelte
Create an RSS Reader in Node
Git Tutorial: Learn how to use Version Control
How to deploy a .NET app using Docker
How to build a Discord bot using TypeScript
Getting Started with Sass
Creating a Twitter bot with Node.js
Getting Started with React
Setting Up Stylus CSS Preprocessor
Setting Up a Local Web Server using Node.js
Using Axios to Pull Data from a REST API
Getting Started with Moon.js
