Juan Urdaneta
Juan Urdaneta

Reputation: 5

ArrayIndexOutOfBoundsException: 1 Error

I have got this error several times and I can't find any solution, I have read in other questions here that it is due to trying to read an array index that doesn't exist. I'm not able to find the problem and it only happens when I send the single quoted string (that is supoused to be a complete JSON but I'm only sending that part for testing, it will throw the same error if a send the complete single quoted JSON) but if I send a simple string such as my name it won't give any problems and print it like it should

public class Parser {

    public String x;    

    public static void main(String[] args) {
        printLn("Hola!");
        String zxc;
        zxc = ("'variable':[1,'Double']}");
        Parse(zxc);
    }
    public static void Parse(String chain){

        int len1 = chain.lastIndexOf("'variable':[");
        int asd = len1+1;
        String[] chainArr = new String[]{chain};
        printLn(chainArr[asd]);


    }

    public static void printLn(String cadena){
        System.out.println(cadena);
    }
    public static void printLn(String[] cadena){
        System.out.println(cadena);
    }
}

EDIT: Error Log says:

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at comp.juan.Parser.Parse(Parser.java:18) at comp.juan.Parser.main(Parser.java:11)"

Please :X

Upvotes: 0

Views: 218

Answers (4)

Juan Urdaneta
Juan Urdaneta

Reputation: 5

Already solve it thanks to Turo in the comments, What I really intended was to get the character at a specific position in the String. I was using indexOf() when I what I wanted to use was charAt().

indexOf would return the position of the character in the string, charAt would return the character, the character was what I wanted.

Upvotes: 0

Zay Ya
Zay Ya

Reputation: 195

I traced your code why you have ArrayIndexOutOfBoundsException, Please see the following..

  int asd = len1+1; //asd =1 
  String[] chainArr = new String[]{chain}; 
  //String[0]='variable':[1,'Double']} 
  System.out.println(chainArr[asd]); //chainArr Array have only zero index.

Upvotes: 0

pbajpai
pbajpai

Reputation: 1377

I agree with @janki, Now If your purpose to parse the json string, you can modify your code as below also:

public static void Parse(String chain){

    String result[] = chain.split(":");
    printLn(result[0]);
    printLn(result[1]);
} 

Hope It may help you write short code for the same purpose.

Upvotes: 0

Janki Gadhiya
Janki Gadhiya

Reputation: 4510

It is because you have only one element in your String Array i.e. at 0th index but you are trying to print other then 0th index. I think 1st or greater '0' in sort.

Your code :

String[] chainArr = new String[]{chain};
printLn(chainArr[asd]);

will convert the whole string 'variable':[1,'Double']} in String Array. So it will become.

chainArr[0] = "'variable':[1,'Double']}";

Upvotes: 4

Related Questions