0

My while loop is going out of the array bounds but I'm not sure where or how to fix it.

import java.util.*;

public class h1n1 {
public static void main(String[]args) {
    Scanner stringScan = new Scanner (System.in);

    String sequence = "asdfkjauiwqeruybnfsdfkjasdfhquegbnasdgf";
    int sequenceLength = sequence.length();
    char[] sequenceArray = sequence.toCharArray();

    System.out.println("Please enter a substring to search: ");
    String userString = stringScan.next();
    char[] userArray = userString.toCharArray();
    int userLength = userString.length();

    int count = 0;
    int numberOfInstances = 0;

    int x = 0;
    int y = 0;

    while (x < sequenceLength) {
        y = 0;
        count = 0;

        while (sequenceArray[x] == userArray[y]) {
            count++;
            x++;
            y++;
        }

        if (count == userLength) {
            numberOfInstances++;
            count = 0;
        }

        else {
            x++;
        }
    }

    System.out.println(numberOfInstances);
    System.out.println(x);


 }
}

The exceptiong error is:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at h1n1.main(h1n1.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

My thought is that I need to subtract one somewhere so that x or y don't go out of bounds but I can't figure out how.

0 Answers0