【问题标题】:I am facing java.lang.StringIndexOutOfBoundsException: [duplicate]我面临 java.lang.StringIndexOutOfBoundsException:[重复]
【发布时间】:2018-05-07 01:50:03
【问题描述】:

我在运行此代码时收到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);
        }
    }
}

【问题讨论】:

  • StringBuilder sb = new StringBuilder() 之后添加这段代码sb.append(str) 或简单地StringBuilder sb = new StringBuilder(str)

标签: java


【解决方案1】:
// 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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多