JavaWorld

Tuesday, June 17, 2014

Handling random objects in Java

The following Java class is handy for test purposes. It allows you to randomly generate a specific type of data with addtional constraints in some of the cases. Assume for exemple that I have a methode m1 in a CharService class, where m1 has the following signature
void m1 (char c);

I want to test the method with only alphabet characters, but would like to use completely randomized choices of character each time the test is called. Then I can use the following method:

public static char anyAlphabetCharacter() {
int mina = 'a';
int minz = 'z';
int maxA = 'A';
int maxZ = 'Z';

int group1Length = minz - mina + 1;
assert (group1Length > 0);

int group2Length = maxZ-maxA + 1;
assert (group2Length > 0);

Random r = new Random();
int groupSelector = r.nextInt() % 2;

int group1Pick = mina +((int) ( r.nextDouble() * (minz-mina)));
int group2Pick = maxA +((int) ( r.nextDouble() * (maxZ-maxA)));

if (groupSelector == 0) {
return (char)group1Pick;
} else {
return (char) group2Pick;
}


}


The full class is:

package org.hypernovae.hyperutils.aleas;

import java.util.Random;

public final class AnyObjects {
private static final Integer HUNDRED_RANGE = Integer.valueOf(100);




public static char anyAlphabetCharacter() {
int mina = 'a';
int minz = 'z';
int maxA = 'A';
int maxZ = 'Z';

int group1Length = minz - mina + 1;
assert (group1Length > 0);

int group2Length = maxZ-maxA + 1;
assert (group2Length > 0);

Random r = new Random();
int groupSelector = r.nextInt() % 2;

int group1Pick = mina +((int) ( r.nextDouble() * (minz-mina)));
int group2Pick = maxA +((int) ( r.nextDouble() * (maxZ-maxA)));

if (groupSelector == 0) {
return (char)group1Pick;
} else {
return (char) group2Pick;
}


}



public static Integer anyIntGreaterThan (Integer minimumValue) {
if (minimumValue == null) {
return Integer.valueOf(1);
} else {

Random r = new Random();
return (minimumValue + r.nextInt(HUNDRED_RANGE));

}
}



public static Object anyObjectIn (Object... objects) {

Random r = new Random();
int elementIndex = r.nextInt(objects.length);
return objects[elementIndex];

}

public static double anyDoubleIn(double... doubles) {
Double[] objDoubles = new Double[doubles.length];
int index = 0;
for (double d:doubles) {
objDoubles[index++] = Double.valueOf(d);
}

return (double)(anyObjectIn((Object[])objDoubles));


}

/**
* Randomly picks up a string among a specified list
* @param strings
* @return
*/
public static String anyStringIn (String...strings) {
Random r = new Random();
int elementIndex = r.nextInt(strings.length);
return strings[elementIndex];
}





public static void main(String[] args) {
String[] elements = {"Monday", "Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};

for (int i = 0; i< elements.length; i++) {
System.out.println(anyStringIn(elements));

}
}

}

0 Comments:

Post a Comment

<< Home