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
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"
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)
}
}