简体   繁体   中英

Getting array out of bounds

I am doing the hacker rank warmups and I have the logic down for repeating strings but am getting an string index out of range and not sure how to fix it. Could someone help with this?

public static long countAs(String s, long n) {

    long count;
    long length = s.length();
    long q = n / length;
    long r = n % length;

    long partial = 0;

    partial = r;

    count = q * getLetterCount(s, q) + getLetterCount(s, partial);


    return count;
}

public static long getLetterCount(String s, long length) {

    long count = 0;


    for (int i = 0; i < length; i++) {

        if (s.charAt(i) == 'a') {

            count++;
        }
    }
    return count;
}

There is only one place in your code where that can happen:

for (int i = 0; i < length; i++) {
    if (s.charAt(i) == 'a') { // <- HERE
        count++;
    }
}

When you are calling s.chartAt(i) most likely i is bigger than the size of the string s . Please check the value of long length you are passing to getLetterCount() .

 for (int i = 0; i < length; i++)

For this line, i is int and length is long, they have different value range! when i = int_max +1 the runtime error will appear

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM