【问题标题】:Compression program gives StringIndexOutOfBoundsException [duplicate]压缩程序给出 StringIndexOutOfBoundsException [重复]
【发布时间】:2021-10-06 00:13:29
【问题描述】:

我正在尝试根据分配规范编写一个删除元音的压缩程序,使用字符串而不是数组,但我不断收到此错误。我完全迷路了。可以使用一些帮助。

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

static String stringCompress(String msg) {

    String vowels = VOWELS;
    String output = "";
    String localChar;

   for (int i = 0; i < msg.length(); i++) {
       localChar = String.valueOf(msg.charAt(i));
       if (!VOWELS.contains(localChar)|| Character.isWhitespace(msg.charAt(i-1))){
           output += localChar;

       }
   }
    return output;

【问题讨论】:

  • 如果您在i 为零时执行msg.charAt(i-1),就会发生这种情况。
  • 也许你可以只保留非元音?
  • 尝试在 java.lang.StringIndexOutOfBoundsException 行捕获您的错误

标签: java compression


【解决方案1】:
Solved

String output = "";
        String localChar;
        if(msg.isEmpty()) {
            output = "";
            return output;
        }
        output = String.valueOf(msg.charAt(0));
       for (int i = 1; i <= msg.length()-1; i++) {
           localChar = String.valueOf(msg.charAt(i));
           if (!VOWELS.contains(localChar)|| Character.isWhitespace(msg.charAt(i-1))){
               output += localChar;

           }
       }

【讨论】:

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