Reputation: 2849
I'm attempting to change a random value in a double. The chosen value is random for the length size of the variable. The method below returns the exact same parameter it takes. Any help please? I want it to return a new changed variable (just change element in the variable). Any help please?
public static double changeRandomValue(double currentVel) {
String text = Double.toString(Math.abs(currentVel));
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;
int nn = text.length();
//rand generates a random value between 0 and nn
int p = rand(0,nn-1);
char ppNew = (char)p;
StringBuilder sb = new StringBuilder(text);
if (text.charAt(ppNew) == '0') {
sb.setCharAt(ppNew, '1');
} else if (text.charAt(ppNew) == '1'){
sb.setCharAt(ppNew, '2');
} else if (text.charAt(ppNew) == '2') {
sb.setCharAt(ppNew, '3');
} else if (text.charAt(ppNew) == '3') {
sb.setCharAt(ppNew, '4');
} else if (text.charAt(ppNew) == '4') {
sb.setCharAt(ppNew, '5');
} else if (text.charAt(ppNew) == '5') {
sb.setCharAt(ppNew, '6');
} else if (text.charAt(ppNew) == '6') {
sb.setCharAt(ppNew, '7');
} else if (text.charAt(ppNew) == '7') {
sb.setCharAt(ppNew, '8');
} else if (text.charAt(ppNew) == '8') {
sb.setCharAt(ppNew, '9');
} else {
sb.setCharAt(ppNew, '0');
}
double newText = Double.parseDouble(text);
return newText;
}
Upvotes: 0
Views: 56
Reputation: 58848
Changing the StringBuilder doesn't change the original String it was made from.
You do this:
StringBuilder sb = new StringBuilder(text);
then change sb
, then do this:
double newText = Double.parseDouble(text);
which still uses the original text.
You can get the modified String from the StringBuilder using its toString
method. Change that line to:
double newText = Double.parseDouble(sb.toString());
Upvotes: 2