将 String 转换为 int 数组,java.lang.ArrayIndexOutOfBoundsException: 6

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20509966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:25:46  来源:igfitidea点击:

Converting String to int array, java.lang.ArrayIndexOutOfBoundsException: 6

javaarraysexceptionuser-interfaceindexoutofboundsexception

提问by Maggy

Here is a little snippet of my code, which is attempting to convert a length 6 string into an int array.

这是我的代码的一小段,它试图将长度为 6 的字符串转换为 int 数组。

int[] intArray=new int[6];
int i = 0;
String s = jTextField2.getText();
int strLength = s.length();
if(strLength != 6) {
  jTextArea1.setText("Not a valid length");
} else {
  for(i=0;i<6;i++) {
    intArray[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
  }
}

This comes up with an out of bounds exception and I cant understand why.

这提出了一个越界异常,我不明白为什么。

Thanks for any help.

谢谢你的帮助。

采纳答案by Elliott Frisch

This

这个

public static void main(String[] args) {
  int[] intArray=new int[6];
  int i = 0;
  String s = "123456";
  int strLength = s.length();
  if(strLength != 6) {
    System.out.println("Not a valid length");
  } else {
    for(i=0;i<6;i++) {
      if (!Character.isDigit(s.charAt(i))) {
        System.out.println("Contains an invalid digit");
        break;
      }
      intArray[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
    }
  }
  System.out.println(Arrays.toString(intArray));
}

Prints

印刷

[1, 2, 3, 4, 5, 6]

here.

这里。