ja233
ja233

Reputation: 23

How to fix Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0?

I am trying to print from my mutable list but keep getting out of bounds. I added the members to the menu at the bottom, then every time I try to print something from a member of a list, I get an error. These members are objects of the class being stored as a list. I am thinking it has to do with the way I wrote the list but I can't figure it out.

I tried adding the members to the list in different ways but it results in the same error.

class membership ()
      {
        var number: Int? = null
        var name: String? = null
        var address: String? = null
        var zip: String? = null
        var phone: String? = null
        var memberSince: String? = null
        var memberType: Char? = null

    }

fun main(args: Array<String>) {

var Members: MutableList<membership> = mutableListOf()

    var member1 = membership()
    member1.number = 1
    member1.name = "George Jetson"
    member1.address ="123 Main St."
    member1.zip = "99207"
    member1.memberSince = "12/01/1997"
    member1.memberType = 'L'

Members[0] = member1

    println(Members[0].name)
}

// I have more members.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
 at java.util.ArrayList.rangeCheck (ArrayList.java:653) 
 at java.util.ArrayList.set (ArrayList.java:444) 
 at FileKt.main (File.kt:45)

Upvotes: 1

Views: 1712

Answers (1)

Christian
Christian

Reputation: 4641

I would say you can not assign item 0, if it has not been set before. The member1 needs to be added with

Members.add(member1)

Upvotes: 3

Related Questions