数组索引超出界限异常 - 如何保持在界限范围内?

时间:2016-02-18 15:27:25

标签: java arrays string exception while-loop

我的while循环不在数组范围内,但我不确定在何处或如何修复它。

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);


 }
}

例外错误是:

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)

我的想法是,我需要在某个地方减去一个,以便x或y不会超出范围,但我无法弄清楚如何。

0 个答案:

没有答案