1

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

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.

6
  • What is the value of s? Commented Dec 11, 2013 at 3:31
  • The length of s is 6. eg: 123456 Commented Dec 11, 2013 at 3:32
  • Looks like your code is ok, but jTextField2.getText() is returning null check that Commented Dec 11, 2013 at 3:33
  • Try with jTextField2.getText().toString(). Just a suggestion Commented Dec 11, 2013 at 3:35
  • 3
    For better help sooner, post an SSCCE. Commented Dec 11, 2013 at 3:36

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.