java.lang.StringIndexOutOfBoundsException: String index out of range: 12 in java

StackOverflow https://stackoverflow.com/questions/21950476

  •  15-10-2022
  •  | 
  •  

سؤال

im trying to get user input a string of 12 numbers and allocate each number into the array space, though im able to allocate the numbers into the array but i got the out of bounds exception at line 12 which i dont understand why. Your help is much appreciated. :)

import java.util.Scanner;

public class Practice
{

    public static void main(String[] args)

    {

        char [] space = new char[13];

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter number ");

        String input = scanner.nextLine();

        for (int i = 0;i<space.length;i++) 
        {
            char bCode = input.charAt(i); 
            space[i] = bCode;       //assign bCode to store in space array
            System.out.println((i+1)+"th " + space[i]);

        }
هل كانت مفيدة؟

المحلول 2

you are checking the space variable length while printing the input values

check the input.length() length instead of space.length length that's why you are getting theStringIndexOutOfBoundsException

change this

 here -> for (int i = 0;i<space.length;i++) 
            {

to this

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

نصائح أخرى

The most likely problem is the String input is not 13 characters long, meaning index 12 is out of bounds, which throws the java.lang.StringIndexOutOfBoundsException. Try checking the length of input before using charAt(i) such as

for (int i = 0; i < space.length; i++) {
    if (input.length() > i) {
        char bCode = input.charAt(i); 
    }
    space[i] = bCode;       //assign bCode to store in space array
    System.out.println((i+1)+"th " + space[i]);
}

or alternatively, you can use this:

for (int i = 0; i < input.length(); i++) {
    char bCode = input.charAt(i); 
    space[i] = bCode;       //assign bCode to store in space array
    System.out.println((i+1)+"th " + space[i]);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top