Madiyar Zhunusov
Madiyar Zhunusov

Reputation: 13

Error in inputting array and outputting it | Kotlin

I am new at Kotlin (and my English is terrible :). I want to define the size of the array and elements in it by inputting it from the keyboard.

fun main() {
   val array_size = readLine()!!.toInt()
   val arr = IntArray(array_size)
   for (i in 0..array_size){
       arr[i] = readLine()!!.toInt()
   }
   
   for(i in 0..array_size){
       println(arr[i])
   }
}

[I got this message][1] [1]: https://i.sstatic.net/DRk9F.png This is my first question in StackOverFlow tho, hope it is understandable for those who want to help.

Upvotes: 1

Views: 54

Answers (2)

k314159
k314159

Reputation: 11062

The NullPointerException is probably because the call to readLine() is returning null and then you're forcing that to non-null using readLine()!! which gives you the NPE.

In recent versions of Kotlin a new method was introduced: readln(). It is recommended to use that instead of the old readLine. If and END OF FILE is found, the new readln method will throw a more descriptive exception, whereas readLine will return null which makes it more difficult to see where you went wrong.

You might get an end-of-file condition if the input is redirected from a file or other source. This often happens if you run your program in an IDE or an online compiler service. If you run your program from the command line, it will work, until you get to enter the last line. This is because for(i in 0..array_size) includes the value array_size which is 1 more than the last index, so you get an out-of-bounds exception.

Instead of using 0..(array_size - 1), it is recommended to use arr.indices which gives you the range of valid indices for the array.

Upvotes: 3

Can_of_awe
Can_of_awe

Reputation: 1556

readLine() is returning null, and so when you do readLine!!... you're getting a NullPointerException. Perhaps you want to use readln instead.

Upvotes: 1

Related Questions