java understands exceptionException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

First of all, this problem is an array out-of-bounds problem.

for example

There is a txt file, and you need to display the content behind the delimiter ----

 The core code of java is

            FileReader fileReader=new FileReader(file);
            reader=new BufferedReader(fileReader);    //缓存类BufferedReader类构造方法
            String line;
            int i=1;
            while ((line=reader.readLine())!=null){
                String[] strs=line.split("----");
                    System.out.println(strs[1]);
            }

An error occurred when running the prompt

reason

After using split to remove the separator, the strings on both sides of the separator will be placed in the string array, and the first line of separators will have no content after them. As a result, there is no strs[1] after the first line is divided, that is, the array is out of bounds.

(When using the split method, when there is no content on the side of the separator, the corresponding array space will not be generated)

String[] strs=line.split("----");

For this code, my modification is to add if to determine the length of the array. If the array length is greater than or equal to 2, then proceed to the next step.

The modified core code below.

            FileReader fileReader=new FileReader(file);
            reader=new BufferedReader(fileReader);    //缓存类BufferedReader类构造方法
            String line;
            int i=1;
            int b=0;
            while ((line=reader.readLine())!=null){
                String[] strs=line.split("----");
                b= strs.length;
                if(b>=2) {
                    System.out.println(strs[1]);
            }

For other situations where the array exceeds the bounds, it can be modified according to the actual situation.

Guess you like

Origin blog.csdn.net/weixin_47406082/article/details/123547407