I am very new in progamming and I want to make a simple task Is it possible to generate a custom char in Java from specific list?
For example, I want that the program would give me random char only from this chars A H F G D
?
Is it possible?
I am very new in progamming and I want to make a simple task Is it possible to generate a custom char in Java from specific list?
For example, I want that the program would give me random char only from this chars A H F G D
?
Is it possible?
There is a simple way to achieve getting pseudorandom element from given set of chars
. You can use Random.nextInt()
(from java.util
package) for that purpose.
You could think of creating an array of char
s, and then let that methods choose an element for you.
Here is an example with the use of Random
class:
char[] array = new char[] {'A', 'H', 'F', 'G', 'D', };
Random rand = new Random();
char chosenOne = array[rand.nextInt(array.length)]; // there is a pseudorandomly chosen index for array in range of 0 inclusive to 5 exclusive
EDIT: According to your comment (you say there that you want to randomly choose elements from set of Strings of various length (that way they are no more char
s (as char
s are a single character - '1
' or '0
', not '10
'), they are String
s then), the most effortless way to achieve that result I can think of, is to put a delimiter between these values in the String. Here is a possible implementation (I made some additional explanations in the comments to the code):
public static void main(String[] args) {
String[] array = splitToSeparateElements("A,H,F,10,G,D,1,0,2000"); // store the result of calling splitToElements() with a
// given String as argument
Random rand = new Random();
for (int i = 0; i < 10; i++) { // this loop is just to print more results to console
System.out.print(array[rand.nextInt(array.length)] + " "); // print pseudorandom element of array to the console
}
}
public static String[] splitToSeparateElements(String inputString) {
String[] splitted = inputString.split(","); // split String to separate Strings in the place of delimiter passed as argument to .split() method
return splitted;
}
Sample output:
D 1 A A 2000 F 10 G 10 A
Yes you can !!
static char getRandomChar(String s){//pass string "AHFGD" here
Random random = new Random();
int index = random.nextInt(s.length());
return s.charAt(index);
}