java - 我面临 java.lang.StringIndexOutOfBoundsException :

标签 java

我收到了 java.lang.StringIndexOutOfBoundsException运行此代码时。我该如何解决这个问题?

import java.util.Scanner;

class C {
    static int Occurence = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        StringBuilder sb = new StringBuilder();
        System.out.println(sb.deleteCharAt(3));
        for (int i = str.length() - 1; i > 0; i--) {
            Occurence = 1;
            for (int j = i - 1; j > 0; j--) {
                if (str.charAt(i) == str.charAt(j)) {
                    Occurence++;
                    sb.deleteCharAt(j);
                }
            }
            System.out.println(str.charAt(i) + " repeated " + Occurence);
        }
    }
}

最佳答案

// empty, current size 0    
StringBuilder sb = new StringBuilder();

// StringIndexOutOfBoundException bcoz current size is 0, and you are accessing index 3.
System.out.println(sb.deleteCharAt(3));

关于java - 我面临 java.lang.StringIndexOutOfBoundsException :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50202567/

相关文章:

java - Knime 中多行的正则表达式

java - 字段上的 Firestore 查询顺序与不同字段上的过滤器

java - 在Java中将 boolean 值转换为int

java - 无法执行 hibernate 查询

java - 从证书中检索主题/CN 字段?

java - 我们可以在 Spring WS 中使用多个消息工厂吗?

Java window 。为什么我可以在命令提示符下运行 jar 文件但不能双击它

java - 使用更新的标记删除 map 上的多个标记

java - 如何将错误消息移动到rabbitmq死信队列

java - 如何在文本字段java中添加文本而不是替换它