简体   繁体   English

关于字符串数组中的String_Index_Out_Of_Bounds_Exception错误

[英]About the String_Index_Out_Of_Bounds_Exception error in string array

String array 字符串数组

I am new to Java and the issue here is not with the total code, it's with array size and out of boundaries issue. 我是Java新手,这里的问题不是总代码,而是数组大小和边界问题。 This code is supposed to simulate the hashing in Java but this is not the main issue though 该代码应该模拟Java中的哈希,但这不是主要问题

Error : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2 错误:线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:2

//import org.w3c.dom.NameList;

public class hash {


  public static void main(String[] args) {

    int tablesize = 4;

    String[] Name = {
      "ALY",
      "om",
      "j",
      "l"
    };

    long Out = calc_hash(Name, tablesize);
    System.out.println(Out);
  }

  public static long calc_hash(String[] key, int table_size) {

    int i, l = key.length;
    long hash = 0;
    for (i = 0; i < l; i++) {

      hash += Character.getNumericValue(key[i].charAt(i));
      hash += (hash << 10);
      hash ^= (hash >> 6);
    }
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    if (hash > 0) return hash % table_size;
    else return -hash % table_size;
  }
}

I don't use Java, but looking at your code I notice this: 我不使用Java,但是在查看您的代码时,我注意到了这一点:

l = key.length

key is the string array, so its length is 4, therefore l = 4 . key是字符串数组,因此其长度为4,因此l = 4 Then you use l as a limit for your loop, you increment i until l - 1 and you use i as an index for both elements in the array and char position in the string ( key[i].charAt(i) ). 然后,将l用作循环的限制,将i递增直到l - 1然后将i用作数组中的两个元素以及字符串( key[i].charAt(i) )中char位置的索引。 This means that if the second string doesn't have at least 2 chars, the 3rd doesn't have at least 3 and the 4th doesn't have at least 4, you will get the error you are getting. 这意味着,如果第二个字符串没有至少2个字符,第三个字符串没有至少3个字符,而第4个字符串没有至少4个字符,则会得到您得到的错误。

Which value from each string do you want to use in each for cycle? 您要在每个for循环中使用每个字符串中的哪个值?

Problem seems to be in your logic. 问题似乎出在您的逻辑上。 All the value in array Name are not of same length. 数组名称中的所有值的长度都不相同。 Once value of i in for loop reach 2, key found is "j" which is of only length 1 and there will be no charAt(2). 一旦for循环中的i in的值达到2,找到的键就是“ j”,其长度仅为1,并且不会有charAt(2)。 Not sure what you are trying to do here but if you have all the elements in array of lenght 4, problem will go away, try with. 不知道您要在这里做什么,但是如果所有元素的长度为4,问题将消失,请尝试一下。

        String[] Name = {
            "ABCD",
            "ABCD",
            "ABCD",
            "ABCD"
    };

Or maybe it's a typo, and should instead 也许这是一个错字,应该改为

hash += Character.getNumericValue(key[i].charAt(0));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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