Mike Goedken Mike Goedken - 1 month ago 7
Java Question

StringIndexOutOfBoundsException with simple string manipulation

public static String replaceChar(String word, char c, int i)
{
if(word.length()<i)
{
System.out.println(word);
}
return word.substring(0, i) + c + word.substring(i + 1);
}


When I use this input below I get an error because the string is not as large as index
i
which is what should happen, but how do I make this error go away by just returning
word
when index
i
is out of range?

System.out.println(replaceChar("run",'a', 3));


This is the error

Exception in thread "main" run
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1931)
at pa5.Hangman2.replaceChar(Hangman2.java:41)
at pa5.Hangman2.main(Hangman2.java:17)

Answer
public static String replaceChar(String word, char c, int i){
    if(0 < i && i < word.length()){
        return word.substring(0, i) + c + word.substring(i + 1);
    }
    return word;
}

It will return the new string only if the given index is valid a positive number less than the length of the given word.

Comments