java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:4

java.lang.StringIndexOutOfBoundsException: String index out of range: 4

我一直在尝试编写一个 Java 程序,将字符串中每个单词的首字母转换为大写字母。现在看起来像这样:

package strings;
import java.util.Scanner;

public class small_cap {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the sentence");
        String st = sc.next();
        String str = " " + st;

        int j = 0; char chr = ' ';

        for (int i = 0; i < str.length(); i++){
            j = i + 1;
            chr = str.charAt(j);
            if (chr == ' '){
                char a = Character.toUpperCase(str.charAt(j));
                str = str.replace(str.charAt(j), a);
            }
            else{
                char a = Character.toLowerCase(str.charAt(j));
                str = str.replace(str.charAt(j), a);
            }
        }
        System.out.println(str);
    }
}

不幸的是,我一直收到错误消息:

java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    at java.lang.String.charAt(String.java:658)
    at small_cap.main(small_cap.java:19)

我真的没有看到代码中有任何错误。有人可以指出我哪里错了吗?

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

i到达最后一个有效索引length - 1时,j将等于length,这是越界的。

我真的不明白 j 变量的意义 - 你是否打算在循环内的其他地方使用 i ,或者你应该只做你的循环从 1 开始?或者你可能是想通过 j = i - 1; 检查前一个字符(在这种情况下确保你没有在索引 0 之前阅读)

  1. 您使用的是 Scanner.next() 而不是 Scanner.nextLine(),它将读取整个句子而不是单个单词。
  2. 您正在字符串中添加额外的 space。不知道这背后的重要原因。没有它也可以做到。
  3. 假设输入是:"abc def" 添加额外的 space 后将变为“abc def”。字符串的长度将变为:7
  4. 现在 for 循环将从 0 迭代到 6。但是在 i = 6 时,它会尝试更改第 7 个位置的元素(因为您正在执行 j=i+1),这将导致字符串索引超出范围错误.
  5. 您正在使用 String.Replace,它将替换所有匹配的字符,而不考虑它们的位置。

    导入java.util.Scanner;

    public class small_cap {
        public static void main(String[] args) {
    
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter the sentence");
            String st = sc.nextLine();
            String str = " " + st;
    
            int j = 0; char chr = ' ';
    
            for (int i = 0; i < str.length()-1; i++){
               j = i+1;
    
                chr = str.charAt(i);
                if (chr == ' '){
                    char a = Character.toUpperCase(str.charAt(j));
                    str = str.substring(0,j)+a+str.substring(j+1);
                }
                else{
                    char a = Character.toLowerCase(str.charAt(j));
                    str = str.substring(0,j)+a+str.substring(j+1);
                }
            }
            System.out.println(str);
        }
    

    }