问题
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);
}
}
}
}
}
Output:
**********************
* 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)
回答1:
Replace
guess2.setCharAt(word.charAt(j), guess);
with
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++) {
回答2:
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.
回答3:
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);
}
result:
Enter a letter: a
-a----
来源:https://stackoverflow.com/questions/26474223/java-replace-a-character-in-a-string