Java - Replace a character in a string


don't think I haven't searched online for an answer. Why is it giving me outofbounds error?

I have two 6-chars long strings. One is "daniel" and another is "------". User enters a character. Loop goes through the "daniel" string and checking char by char is they match with the user input. If it matches, it should replace the guessed char with the one in "------". So if you input 'a' it should output "-a----" and the loop continues. Next if you enter 'e' it should output "-a--e-" etc. Code gives no compilation error or any warning and also makes perfect sense. I tried substring and replace but this is simpler and shorter. I tried debugging it but it gives no useful info. I don't know why is it returning outofbounds error.

package hello.world; import java.util.Scanner; public class HelloWorld { public static void main(String[] args) { Scanner in=new Scanner(System.in); String word="daniel"; StringBuilder guess2 = new StringBuilder("------"); char guess; System.out.println("**********************"); System.out.println("* Welcome to Hangman *"); System.out.println("**********************"); for (int i=0;i<10;i++) { System.out.print("Enter a letter: "); guess=in.nextLine().charAt(0); for (int j=0;i<word.length();j++) { if (guess==word.charAt(j)) { guess2.setCharAt(word.charAt(j), guess); System.out.print(guess2); } } } } }


********************** * Welcome to Hangman * ********************** Enter a letter: a Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 97 at java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:380) at java.lang.StringBuilder.setCharAt(StringBuilder.java:76) at hello.world.HelloWorld.main(HelloWorld.java:22) Java Result: 1 BUILD SUCCESSFUL (total time: 2 seconds)



guess2.setCharAt(word.charAt(j), guess);


guess2.setCharAt(j, guess);

The first parameter is the index of the character to replace in the StringBuilder, not the character itself.

Also, there seems to be a typo in the for loop using i instead of j.

for (int j=0;i<word.length();j++) {


String.length() returns the length of string starting from 1 and not from 0. So whenever you use String.length() always use less than (<) symbol.


Instead of using the String builder you can just replace everything using regex + replaceAll method

for (int i=0;i<10;i++) { System.out.print("Enter a letter: "); guess=in.nextLine().charAt(0); word = word.replaceAll("[^"+ guess +"]", "-"); System.out.println(word); }


Enter a letter: a -a----


  • add and remove classes in order with jQuery
  • Finding matching phrases between two pieces of text?
  • Wait for a SLOT to finish the execution with Qt
  • Calculate all possible factors of a prime
  • Convert array of strings to array of objects
  • Displaying iOS iAds only to supported countries
  • Why does Redshift need to do a full table scan to find the max value of the DIST/SORT key?
  • Does Perl currently (5.8 and 5.10) make any promises about the order alternations will be used?
  • Net-ssh session timeout
  • pyspark substring and aggregation
  • Best Datagrid for Bootstrap/jQuery?
  • WebApp in AppServices vs CloudService
  • Update varbinary(MAX) field in SQLServer 2012 Lost Last 4 bits
  • Python adding lots of things to PATH. How do I stop?
  • remove unicode characters but keep all special and English characters with preg_replace
  • Replace last two characters in column
  • (Tcl/Expect) clear screen after exit
  • Scanner nextInt() and hasNextInt() problems
  • Spring integration inbound-gateway Fire an event when queue is empty
  • Retrieving specified columns from a list of csv files to create a data data frame in R
  • jQuery: How to AJAXify WordPress Search?
  • Possible to “watch” both HAML and SASS at the same time?
  • Filter strings with regex before casting to numeric
  • Trying to get the char code of ENTER key
  • Debugging VB6 Code From Visual Studio 2010
  • C# program and C++ DLL compiled for 32-bit system crash on 64-bit system
  • How solve “Qt: Untested Windows version 10.0 detected!”
  • C: Incompatible pointer type initializing
  • debug library loaded with ctypes using gdb
  • Mysterious problem with floating point in LISP - time axis generation
  • How to know when stdin is empty if it contains EOF?
  • Can you perform a UNION without a subquery in SQLAlchemy?
  • D3 nodes and links from JSON with nested arrays of children
  • Debugging ASP.NET on a built-in web server suddenly stops
  • Get object from AWS S3 as a stream
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Function pointer “assignment from incompatible pointer type” only when using vararg ellipsis
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • MATLAB: Piecewise function in curve fitting toolbox using fittype
  • Reading document lines to the user (python)