- Trending Categories
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
How to populate a 2d array with random alphabetic values from a range in Java?
To populate a 2d array with random alphabets, use the Random class. Let us first declare a 2d array −
char arr[][] = new char[3][3];
Now, in a nested for loop, use the Random class object to get random values on the basis of switch case. Here, our range is 3 i.e. set of 3 alphabets at once −
Random randNum = new Random(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int x = randNum.nextInt(3); switch (x) { case 0: { arr[i][j] = 'p'; break; } case 1: { arr[i][j] = 'q'; break; } . . . } } }
Now, for the string representation of the random alphabets in a range, which is 3 −
Arrays.deepToString(arr)
Example
import java.util.Arrays; import java.util.Random; public class Demo { public static void main(String[] args) { char arr[][] = new char[3][3]; Random randNum = new Random(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int x = randNum.nextInt(3); switch (x) { case 0: { arr[i][j] = 'p'; break; } case 1: { arr[i][j] = 'q'; break; } case 2: { arr[i][j] = 'r'; break; } case 3: { arr[i][j] = 's'; break; } case 4: { arr[i][j] = 't'; break; } case 5: { arr[i][j] = 'u'; break; } case 6: { arr[i][j] = 'v'; break; } case 7: { arr[i][j] = 'w'; break; } } } } System.out.println("Random alphabets..."); System.out.println(Arrays.deepToString(arr)); } }
Output
Random alphabets... [[q, q, p], [p, p, q], [p, p, p]]
Advertisements