Java Index 1 out of bounds for length 1 error question.

Asked 2 years ago, Updated 2 years ago, 139 views

12345678 1 lee1 010-1231-5678 // 11345678 2 lee2 010-1232-5678 ...... An example of reading a file with these characters, separating it into objects, and storing them as files.

But you have to separate num, grade, name, and tel_number and save it as an object.


for(int i = 1; (line = br.readLine()) != null; i++) {
            System.out.println(line);
            //String str = null;
            String[] a = line.split("\n");
            For(int x = 0; a[x]!= null; x++)// error-prone part {
                    String[] b = a[x].split(" ");

                su.num = b[0];
                su.grade = Integer.parseInt(b[1]);
                su.name = b[2];
                su.tel_number = b[3];
            }

Since I'm doing it, In the error-prone part,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at myPack.p1.Student.main(Student.java:33).

I know that this error occurred, but I don't know how to find the end of the array.

java arrayindexoutofboundsexception

2022-09-22 16:12

2 Answers

// Enter your code here
for(int x =0; x<a.length ; x++) {
   ...
}

http://mwultong.blogspot.com/2006/11/java-array-size-sizeof.html Please refer to it.


2022-09-22 16:12

String[] a = line.split("\n");
for (String oenRaw : a) {
    // oenRaw can be obtained sequentially from the 0th in the array.
}

You can also use for each loop in this way


2022-09-22 16:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.