单独计算单词和空格的Java程序,但该程序显示:线程“ main”中的异常java.lang.StringIndexOutOfBoundsException:

问题描述 投票:0回答:1
import java.io.*;
import java.lang.*;
import java.util.*;

public class CountWords_Spaces {
   public static void main(String[] args) throws IOException {
      String str = "Hello World";
      int i = 0, w = 0, s = 0, l, j = 0;
      l = str.length();
      for (i = 0; i < l; i++) {
         if (str.charAt(i) != ' ' && str.charAt(i) != '\t') {
            w++;
            while (str.charAt(i) != ' ' && str.charAt(i) != '\t') {
               i++;
            }
         }
         s++;
      }
      s--;
      System.out.println(str.charAt(1));
      System.out.println("No of Words: " + w);
      System.out.println("No of Spaces: " + s);
   }
}
java count word
1个回答
0
投票

每次增加i时,您都必须测试未通过输入str的长度。更改

while (str.charAt(i) != ' ' && str.charAt(i) != '\t') {

包括对i < l之类的测试

while (i < l && str.charAt(i) != ' ' && str.charAt(i) != '\t') {

有了这一改变,我得到了

e
No of Words: 3
No of Spaces: 2
© www.soinside.com 2019 - 2024. All rights reserved.