I have an array of integers that I'm randomizing using a method, and I want to convert that array of integers using
int[] prizesUnshuffled = {0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5};
RandomizeArray(prizesUnshuffled);
String[] prizesString = (generateStringArray(prizesUnshuffled));
What I want is for instance, the unshuffled array to then be
String[] prizesString = {PrizeA, PrizeA, PrizeA, PrizeB, PrizeB, PrizeB, PrizeC, PrizeC, PrizeC, PrizeD, PrizeD, PrizeD, PrizeE, PrizeE, PrizeE, PrizeF, PrizeF, PrizeF, PrizeF, PrizeF, PrizeF, PrizeF, PrizeF, PrizeF, PrizeF};
Sorry if I'm bad at explaining this, but I have no clue how to accomplish this, as I'm new to using arrays.
Java 8's Stream API can make this a trivial one-liner:
int[] arr = { 1, 2, 3, 4, 5 };
String[] arr_toString = Arrays.stream(arr).boxed().map(x -> "Prize" + x).toArray(String[]::new);
If you don't have access to the stream API, or would prefer something else, you can also do:
int[] arr = { 1, 2, 3, 4, 5 };
String[] arr_toString = new String[arr.length];
for (int i = 0; i < arr.length; ++i) {
arr_toString[i] = "Prize" + arr[i];
}
public String[] generateStringArray(int[] prizesUnshuffled) {
// Create string array of same size as we are going to return the same size
String[] stringArr = new String[prizesUnshuffled.length];
String prepend = "Prize";
// Sort the prizesUnshuffled as it's been randomized by RandomizeArray
Arrays.sort(prizesUnshuffled);
// Iterate till there are items in prizesUnshuffled
for (int i = 0; i < prizesUnshuffled.length; i++) {
// Concat the string with prizedUnshuffled
// Replace it in generate string array
stringArr[i] = prepend + prizesUnshuffled[i];
}
return stringArr;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.