【问题标题】:Java For Loop Trouble, Index ErrorsJava For 循环故障,索引错误
【发布时间】:2017-12-31 19:07:59
【问题描述】:
class Main{
    public static void main (String str[]) throws IOException{
      Scanner scan = new Scanner (System.in);
      String message = scan.nextLine();
      String[] sWords = {" qey ", " $ "," ^^ "};
      int lenOfArray = sWords.length;
      int c = 0;  
      int[] count = {0,0,0};  

在 for 循环之一中出现错误 "java.lang.StringIndexOutOfBoundsException: String index out of range: -1" 。我希望程序检查 sWord 数组中的每个子字符串,并计算它在主消息输入中出现的次数。

  for (int x = 0; x < sWords.length; x++){
    for (int i = 0, j = i + sWords[x].length(); j < message.length(); i++){
      if ((message.substring(i,j)).equals(sWords[x])){
        count[c]++;
        }
      }
    }
  }
}

【问题讨论】:

标签: java for-loop indexoutofboundsexception


【解决方案1】:

按照您的方法,您需要在内部循环中设置 j 的值。否则,仅在第一次迭代时分配。这将更改内部 for 循环的上限,如下所示。您还需要在搜索sWord 后增加计数器索引c

import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class MyClass {
    public static void main (String str[]) throws IOException {
        Scanner scan = new Scanner(System.in);
        String message = scan.nextLine();
        String[] sWords = {" qey ", " $ ", " ^^ "};
        int lenOfArray = sWords.length;
        int c = 0;
        int[] count = {0, 0, 0};
        for (int x = 0; x < sWords.length; x++) {
            for (int i = 0; i <= message.length()-sWords[x].length(); i++) {
                int j = i + sWords[x].length();
                if ((message.substring(i, j).equals(sWords[x]))) {
                    count[c]++;
                }
            }
            ++c;
        }
    }
}

【讨论】:

    【解决方案2】:

    您可以在下面的代码中找到sWords 中每个字符串的出现次数:

    public static void main(String[] args) { 
        try {
            Scanner scan = new Scanner(System.in);
            String message = scan.nextLine();
            String[] sWords = {" qey ", " $ ", " ^^ "};
            int lenOfArray = sWords.length;
            int c = 0;
            int[] count = {0, 0, 0};
            for (int i = 0; i < lenOfArray; i++) {
                while (c != -1) {
                    c = message.indexOf(sWords[i], c);
                    if (c != -1) {
                        count[i]++;
                        c += sWords[i].length();
                    }
                }
                c = 0;
            }
            int i = 0;
            while (i < lenOfArray) {
                System.out.println("count[" + i + "]=" + count[i]);
                i++;
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
    

    【讨论】:

      【解决方案3】:

      最好用apache commons lang StringUtils

      int count = StringUtils.countMatches("a.b.c.d", ".");
      

      【讨论】:

        猜你喜欢
        • 2015-11-10
        • 1970-01-01
        • 2017-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多