Java-替换字符串中的字符 [英] Java - Replace a character in a string

查看:91
本文介绍了Java-替换字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不要以为我没有在线搜索答案。为什么会给我出站错误?

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

我有两个6个字符的长字符串。一个是丹尼尔,另一个是 ------。用户输入一个字符。循环遍历 daniel字符串,并逐字符检查char是否与用户输入匹配。如果匹配,则应将猜测的char替换为 ------中的char。因此,如果您输入 a,则应输出 -a ----,然后循环继续进行。接下来,如果您输入 e,则应输出 -a--e-等。代码不会给出编译错误或任何警告,也很有意义。我尝试了子字符串并替换,但这更简单,更短。我尝试调试它,但没有提供有用的信息。我不知道为什么会返回出站错误。

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

第一个参数是 StringBuilder <中要替换的字符的索引/ code>,而不是角色本身。

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

此外,中似乎有错字 c >使用 i 而不是 j 循环。

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

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

这篇关于Java-替换字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆