- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to generate random numbers string
At first, create a character array −
static char num[] = { '0', '1', '2', '3', '4', '5' };
Now, let’s say you want to a string with length. Create a StringBuilder and use append() to create random numbers string out of it −
int len = 5; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < len; i++) { strBuilder.append(randomNum()); }
Above, we created a randomNum() function that returns the random numbers string −
public static char randomNum() { return num[(int) Math.floor(Math.random() * 5)]; }
Example
public class Demo { static char num[] = { '0', '1', '2', '3', '4', '5' }; public static char randomNum() { return num[(int) Math.floor(Math.random() * 5)]; } public static void main(String[] args) { int len = 5; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < len; i++) { strBuilder.append(randomNum()); } System.out.println("Random numbers string = "+strBuilder.toString()); } }
Output
Random numbers string = 23024
Advertisements