Search code examples
javaarraysintegertext-manipulation

Integer.valueOf() Error ArrayIndexOutOfBoundsException:


String currentLine = reader.readLine();
while (currentLine != null)
{
  String[] studentDetail = currentLine.split("");

  String name = studentDetail[0];

  int number = Integer.valueOf(studentDetail[1]);
  currentLine = reader.readLine();
}

So I have a file like this:

   student1
   student16
   student6
   student9
   student10
   student15

When I run the program said: ArrayIndexOutOfBoundsException:1

the output should look like this:

   student1
   student6
   student9
   student10
   student11
   student15
   student16

Solution

  • First, program to the List interface instead of the ArrayList concrete type. Second, use a try-with-resources (or explicitly close your reader in a finally block). Third, I would use a Pattern (a regex) and then a Matcher in the loop to look for "name" and "number". That might look something like,

    List<Student> student = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(new File(infile)))) {
        Pattern p = Pattern.compile("(\\D+)(\\d+)");
        String currentLine;
        while ((currentLine = reader.readLine()) != null) {
            Matcher m = p.matcher(currentLine);
            if (m.matches()) {
                // Assuming `Student` has a `String`, `int` constructor
                student.add(new Student(m.group(1), Integer.parseInt(m.group(2))));
            }
        }
    } catch (FileNotFoundException fnfe) {
        fnfe.printStackTrace();
    }
    

    Finally, note that Integer.valueOf(String) returns an Integer (which you then unbox). That is why I have used Integer.parseInt(String) here.