0
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};  

Getting the error, "java.lang.StringIndexOutOfBoundsException: String index out of range: -1" , in one of the for loops. I want the program to check for each substring in the sWord array and count how many times it occurs in the main message input.

  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]++;
        }
      }
    }
  }
}
Ryan C
  • 1

3 Answers3

0

Following your approach, you need to set the value of jwithin the inner loop. Otherwise, it is only assigned on the first iteration. This changes the upper bound in the inner for loop as shown below. You also need to increment the counter index c after you search for an sWord.

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;
        }
    }
}
drumhellerb
  • 381
  • 1
  • 7
0

You can find number of occurrences of each string in sWords in the code below:

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();
    }
}
M.Shirzad
  • 1
  • 2
-2

It's better to use apache commons lang StringUtils

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