No, not like this:
String stringName = "example";
String stringName2 = ("\"" stringName "\" secretly means \"i like trains\"");
The code i tried to use is:
long amountOfChars = chars.length;
int amountOfTimesLeft = 20;
String out = null;
Random random = new Random();
while (amountOfTimesLeft != 0) {
long whichChar = (random.nextInt((int) (amountOfChars - 0 1)) 0);
StringBuilder sb = new StringBuilder(chars[(int) whichChar]);
sb.append(out);
}
("chars" is an array of strings ive already defined)
What i expected it to do is: Get a random string from the chars array and add it to the out string, and repeat it 19 more times
What it does:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 32 out of bounds for length 32
at Main.main(Main.java:45)
I have really no idea what this means. Could someone help? (line 45 is the line that defines sb)
and yes, i know i forgot to decrease amountOfTimesLeft, but thats not the point of this question.
CodePudding user response:
ArrayIndexOutOfBoundsException means that index for array chars
is out of bounds.
That means that array chars
has less than 32 available indexes (length of array is 32 or less). You can see in exception message: Index 32 out of bounds for length 32
. Length of that array is 32, which means available indexes are from 0 to 31 inclusive. Java counts array indexes from 0.
However your usage of StringBuilder class is wrong. In that cycle you are creating new instance of StringBuilder every iteration StringBuilder sb = new StringBuilder(chars[(int) whichChar]);
. Create StringBuilder instance once before cycle and then just use append method.
You are also always appending null
to sb
since out
is always null
.
Also make sure you manipulateamountOfTimesLeft
, becuase this way the cycle will be infinite.
Example solution:
long amountOfChars = chars.length -1; //-1 to prevent ArrayIndexOutOfBoundsException
int amountOfTimesLeft = 20;
Random random = new Random();
StringBuilder sb = new StringBuilder();
while (amountOfTimesLeft != 0) {
long whichChar = (random.nextInt((int) (amountOfChars - 0 1)) 0);
sb.append(chars[(int) whichChar]);
amountOfTimesLeft--; //decrease amountOfTimesLeft by 1
}
To get the actual String
you can do sb.toString()
;
CodePudding user response:
I made a little change to your code.
To make int random in a range, we use random.nextInt(max - min) min. Here max is the max array index, the min is the index 0.
I moved the StringBuilder out of the loop. Reduce the condition value to break out of the loop when the condition is met.
Please be aware of casting long to int, it can lead to an Overflow issue.
char[] chars = {'a', 'b', 'c', 'd'};
long amountOfChars = chars.length;
int amountOfTimesLeft = 20;
Random random = new Random();
StringBuilder sb = new StringBuilder();
while (amountOfTimesLeft != 0)
{
long whichChar = (random.nextInt((int)(amountOfChars - 0)) 0);
sb.append(chars[(int)whichChar]);
amountOfTimesLeft--;
}
System.out.println(sb.toString());