omlfc be omlfc be - 15 days ago 8
Java Question

replacing the character with the smallest assigned ASCII number with a random character java

I'm trying to replace the character with the smallest assigned ASCII number in a string with a random character generated within a range.

here's the code:

import java.util.*;

public class TestMethod {

Random rn = new Random();
public synchronized void test(String st){
while(true){
char c = (char)rn.nextInt(((126-33)+1)+33);
int min = (int)st.charAt(0);
int index = 0;

for(int i=0; i<st.length(); i++){
if((int)st.charAt(i) < min){
min = (int)st.charAt(i);
index = st.indexOf(i);
}
}
String newst = st.substring(0, index) + c + st.substring(index+1, st.length());

try{
Thread.sleep(2000);
System.out.println(newst);
}catch(Exception e){
e.printStackTrace();
}

//checks if all characters equal to '~'
ArrayList<String> stArr = new ArrayList<String>();
stArr.add(newst);
for(String i : stArr){
if(i.length()-i.replace("~", "").length() == 0){
break;
}
}
}
}


}

I get a runtime error :

java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at TestMethod.test(TestMethod.java:18)
at classA.run(classA.java:16)
at java.lang.Thread.run(Unknown Source)


at this line :

String newst = st.substring(0, index) + c + st.substring(index+1, st.length());


what is it that i'm doing wrong ? i've just started experimenting with synchronized.

Answer

The line

index = st.indexOf(i);

should be

index = i;