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 Express
Create an RSS Reader in Node
Getting Started with Electron
How to build a Discord bot using TypeScript
How to deploy a PHP app using Docker
Getting Started with Deno
Learn how to use v-model with a custom Vue component
Build a Real-Time Chat App with Node, Express, and Socket.io
Getting User Location using JavaScript's Geolocation API
Getting Started with React
Getting Started with Vuex: Managing State in Vue
