0

Main program:

System.out.print("Enter the new student name: ");
String studName = input.nextLine();
newCourse.addStudent(studName);

class:

public void addStudent(String studName){
        studentNames[noOfStudents] = studName;
        noOfStudents++;
    }

After run it show me this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

2 Answers2

1

If you want to use an Array, since its not expendable, you need to creat a copy of the underlying Array with one more index than the original one to put the wanted element in it.

This example uses an own method to do so:

public static void main(String[] args) {
    final int [] start = {1,7,-4},
    added = append(start, 77);
    System.out.println("added: " + Arrays.toString(added));
  }

static public int[] append(final int[] values, final int newValue) {
  final int[] result = Arrays.copyOf(values, values.length + 1);
  result[values.length] = newValue;
  return result;}
Hannes
  • 93
  • 5
0

Using arrays for operations like add/remove is not recommended. Start using lists will make your life easier. Following your example with lists

List<String> students = new ArrayList<>();
System.out.print("Enter the new student name: ");
String studentName = input.nextLine();
students.add(studentName);

System.out.println("Number of students: " + students.size());

Traycho Ivanov
  • 2,887
  • 14
  • 24