简体   繁体   English

Java-替换字符串中的字符

[英]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. 我有两个6个字符的长字符串。 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. 循环遍历“ daniel”字符串,并逐字符检查char是否与用户输入匹配。 If it matches, it should replace the guessed char with the one in "------". 如果匹配,则应将猜测的char替换为“ ------”中的char。 So if you input 'a' it should output "-a----" and the loop continues. 因此,如果输入“ a”,则应输出“ -a ----”,然后循环继续。 Next if you enter 'e' it should output "-a--e-" etc. Code gives no compilation error or any warning and also makes perfect sense. 接下来,如果输入“ e”,则应输出“ -a--e-”等。代码不给出编译错误或任何警告,并且也很有意义。 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)

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. 第一个参数是要在StringBuilder替换的字符的索引,而不是字符本身。

Also, there seems to be a typo in the for loop using i instead of j . 另外,似乎在使用i而不是jfor循环中有错别字。

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

String.length()返回从1开始而不是从0开始的字符串的长度。因此,每当您使用String.length()时,始终使用小于(<)符号。

Instead of using the String builder you can just replace everything using regex + replaceAll method 除了使用String builder您还可以使用正则表达式+ replaceAll方法替换所有内容

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----

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM