1

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.

1

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It's very cool that the community here answers so fast.
1

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

1 Comment

Appreciate it!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.