Skip to main content
 首页 » 编程设计

java之在 Java 中使用 for 循环获取超出范围的字符串索引

2024年06月20日208JeffreyZhao

我有一个 for 循环来从字符串中删除元音,但如果字符串以元音结尾,我会收到错误消息。如果字符串不以元音结尾并打印出结果就好了,但如果它以元音结尾,它将不起作用,我得到错误。我该如何解决这个问题?

package program5; 
 
import java.util.Scanner; 
 
public class Disemvoweling { 
public static void main(String[] args) { 
      Scanner scnr = new Scanner(System.in); 
 
      String phrase; 
      System.out.println("Welcome to the disemvoweling utility."); 
      System.out.print("Enter your phrase: "); 
      phrase = scnr.nextLine();        
      int inputLength = phrase.length(); 
 
      for (int i = 0; i < phrase.length(); i++) { 
          if (phrase.charAt(i) == 'a') { 
              phrase = phrase.replace("a",""); 
          } 
          if (phrase.charAt(i) == 'e') { 
              phrase = phrase.replace("e",""); 
          } 
          if (phrase.charAt(i) == 'i') { 
              phrase = phrase.replace("i",""); 
          } 
          if (phrase.charAt(i) == 'o') { 
              phrase = phrase.replace("o",""); 
          } 
          if (phrase.charAt(i) == 'u') { 
              phrase = phrase.replace("u",""); 
          } 
      } 
      System.out.println("The disemvolwed phrase is: " + phrase); 
      int inputAfter = phrase.length(); 
      System.out.print("Reduced from " + inputLength + " characters to " + inputAfter + " characters. "); 
      double percentage = (double) inputAfter / inputLength * 100;  
      double percentageRounded = (double) percentage % 1; 
      System.out.print("Reduction rate of " + (percentage - percentageRounded) + "%"); 
 
 
} 
 
} 

请您参考如下方法:

异常是由 charAt 生成的功能:

Throws: IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

问题是当你执行这段代码时:

phrase = phrase.replace("a",""); 

你缩短了字符串。如果这发生在字符串的最后一个字符上,下一个 chartAt 会生成超出范围的索引:

 // Now phrase is shorter and i is over the lenght of the string 
 if (phrase.charAt(i) == 'e') { 
     phrase = phrase.replace("e",""); 
 } 

解决方案是每次执行替换继续到下一个循环。

   for (int i = 0; i < phrase.length(); i++) { 
      if (phrase.charAt(i) == 'a') { 
          phrase = phrase.replace("a",""); 
          continue;  // Continue to the next loop if a has been found 
      } 
      .... 
  } 

较短的解决方案将使用方法 replaceAll如下:

 phrase = phrase.replaceAll("[aeiou]",""); 

其中 [aeiou] 是匹配任意字符 a, e, i, o, u 的正则表达式