Take input in array with loop

Viewed 6657

developers, i am new in Kotlin I am trying to take input in Array by using loop and after that, i print the all values of array by using loop but t get only input and not show the other chunk and through the error which is shiwn on attach image

enter image description here

    fun main(args: Array<String>) {

    var arrayint = Array<Int>(5){0}
    var x = 1
        val abc:Int = arrayint.size
     while( x <= abc)
     {
         arrayint[x] = readLine()!!.toInt()
            x++
     }


   for(index in 0..4)
   {
       println(arrayint[index])
   }

}
6 Answers

Try this:

fun main (args:Array<String>){

    var arrayint = Array<Int>(5){0}
    var x:Int = 0
    val abc:Int = arrayint.size
    while( x < abc)
    {
        arrayint[x] = readLine()!!.toInt()
        x++
    }

    for(index in 0..4)
    {
        println(arrayint[index])
    }
}

One of the shorthand for taking n data elements of data input in an array of predefined size is as follow. Here the user is going to input a integer
n = number of elements then then the array elements


import java.util.*

fun main(){
    val read = Scanner(System.`in`)
    
    val n = read.nextInt()

    var arr = Array(n) {i-> read.nextInt()} // taking input

    arr.forEach{
        println(it) // this loop prints the array
    }   
   
}

Following code is taking input in array using loop

import java.util.*
fun main(args: Array<String>) {

    var num = arrayOfNulls<Int>(5)
    var read= Scanner(System.`in`)
    println("Enter array values")
    for(i in 0..4)
    {
        num[i] = read.nextInt()
    }
    println("The array is")

    for(x in num){
        println(x)}
    }

Following code is taking input of array size and then it's elements

fun main() {

    print("Enter Array size: ")
    val arraySize = readLine()!!.toInt()
    println("Enter Array Elements")
    val arr = Array<Int>(arraySize) { readLine()!!.toInt() }

    for (x in arr)
        println(x)
}
Related