简体   繁体   中英

Java String index out of bound

Sir here i am trying to check is there any number is exists or not . if there any digit exists then it will print the digit. But when i am trying to run this code i am facing error. please help me to fix the error.

My code

import java.util.Scanner;
public class test1{
  public static void main (String[] args){
    Scanner input = new Scanner(System.in);
    int a = input.nextInt();
    String arr[]= new String[a];
    for(int i=0;i<a;i++){
        arr[i]=input.next();
    }
    for(int i=0;i<a;i++){
        String sub[] = arr[i].split("");
        for(int j=0;j<sub.length;j++){
            char x = arr[i].charAt(j);
            if(Character.isDigit(x)){
                System.out.println(x);
            }
        }
    }   
  }
}

I am getting this error :

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    at java.lang.String.charAt(String.java:686)
    at test1.main(test1.java:13)
Java Result: 1

Would you please help me to fix this problem.

Instead of using String.split , convert your string into a character array:

try (Scanner input = new Scanner(System.in)) {
  System.out.print("Enter number of strings: ");
  int a = input.nextInt();

  String arr[] = new String[a];
  for (int i = 0; i < a; i++) {
    System.out.print(String.format("Enter string #%d: ", i + 1));
    arr[i] = input.next();
  }

  for (int i = 0; i < a; i++) {
    for (char c : arr[i].toCharArray()) {
      if (Character.isDigit(c)) {
        System.out.println(c);
      }
    }
  }
}

Note: I put your Scanner in a try-with-resources construct, since you weren't closing it correctly.

Example usage:

Enter number of strings: 3
Enter string #1: abc
Enter string #2: 1abc
Enter string #3: a1b2c3
1
1
2
3

Use string.lenght() :

String sub[] = new String[arr[i].lenght()];
            for(int j=0;j<arr[i].length();j++){
                char x = arr[i].charAt(j);
                if(Character.isDigit(x)){
                System.out.println(x);
            }
}

Edit: The array sub[] isn't even used, so it doesn't have to be declared at all.

Change

 for(int j=0;j<sub.length;j++)

to

for(int j=0;j<sub.length-1;j++)

I tested it and it works as expected :)

Thats is because the length of sub is 5 when the input string have a length of 4. For example: input hello have a length of 5 and after do split("") it has a length of 6 because it is ""+"h"+"e"+"l"+"l"+"o" in the array. So the String in sub is one index bigger than the String in the array :)

If you use String.split("") directly to build an String[] array. The first one is empty.

Let's split string " 123 " for example, you will gain a String[] array as [,1,2,3] , rather than [1,2,3] .

 String[] text = "123".split("");
 //[, 1, 2, 3]
 System.out.println(Arrays.toString(text));

This extra empty is the cause of Exception : StringIndexOutOfBoundsException:

You can skip the first empty string, and start the index from 1 instead of 0 .

Change the following code

from

   for(int i=0;i<a;i++){
        String sub[] = arr[i].split("");
        for(int j=0;j<sub.length;j++){
            char x = arr[i].charAt(j);
            if(Character.isDigit(x)){
            System.out.println(x);
            }
        }
    }   

to

    for(int i=0;i<a;i++){
        String sub[] = arr[i].split("");
        for(int j=1;j<sub.length;j++){
            char x = arr[i].charAt(j-1);
            if(Character.isDigit(x)){
            System.out.println(x);
            }
        }
    } 

and you will get the expected result, an example is run as follows:

2
12dec
34
1
2
3
4

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