0
class MusicPlayer { private var songs: Array<String> = arrayOf("") var index = songs.size fun add(track: String) { songs[index-1] = track } fun show() { for (item in songs) { println(item) } } } fun main(args: Array<String>) { val m = MusicPlayer() while(true) { var input = readLine()!! if(input == "stop") { break } m.add(input) } m.show() } 

my inputs are

>Purple Haze >Under Pressure >Walk This Way >stop 

expected output

>Purple Haze >Under Pressure >Walk This Way >Playing Purple Haze 

but what i get is

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 0

2
  • 2
    Don't use Array unless you need a collection that never changes size. Use List/MutableList. Commented Mar 23, 2021 at 14:14
  • Alright, thanks Tenfour04 Commented Mar 24, 2021 at 9:58

2 Answers 2

1

add function in MusicPlayer class has no sense. First, imagine first three iterations. We call add method 3 times, like this:

m.add("song1") m.add("song2") m.add("song3") 

In MusicPlayer it will look like this: (You are not modifying "index" variable anywhere, so...)

// index = 1 // songs[index - 1] = songs[1 - 1] = songs[0] //first add songs[0] = "song1" //second add songs[0] = "song2" //third add songs[0] = "song3" 

Second, the size of the array is not dynamic. If you declare an array with size = 1, its size will always be 1. You can't do something like that
private var songs: Array<Stirng> = arrayOf("") songs[2] = "exampleText" //ArrayIndexOutOfBoundsException 

Array reserved memory for just 1 element. There are ways to deal with it, but in your example, I recommeng you to use ArraysList or MutableList (Almost the same). Such collection allows you to freely modify it's size/length.

Your MusicPlayer with ArrayList would look like this

 private var songs: ArrayList<String> = ArrayList() fun add(track: String) { songs.add(track) } fun show() { for (item in songs) { println(item) } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much I'll not forget that.
1

If you work with a mutable list, you don't need an index-variable. With mutable list it is much easier than with an array.

class MusicPlayer { private val songs = mutableListOf<String>() fun add(track: String) { songs.add(track) } fun show() { for (item in songs) { println(item) } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.