Reputation: 87
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
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])
}
}
Upvotes: 2
Views: 9441
Reputation: 33
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 } }
Upvotes: 1
Reputation: 53
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)
}
Upvotes: 0
Reputation: 1
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)}
}
Upvotes: 0
Reputation: 26
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])
}
}
Upvotes: 1
Reputation: 10605
The following is a little more succinct
var arrayint = Array<Int>(5) { readLine()!!.toInt() }
for(x in arrayint)
println(x)
On the first line, instead of using the initializer lambda { 0 }, I use a lambda that call readLine. On line 2, instead of having to know my range (0..4), I let the language do it for me (an Array is iterable).
Upvotes: 3
Reputation: 9488
You should change x <= abc
to x < abc
and x = 1
to x = 0
. It doesn't work now because if abc = 5
and you loop 4 times then x = 5
but arrays in Kotlin (and Java) start at index 0 which means that array of size 5 has the following indexes: 0, 1, 2, 3, 4
which means that arrayint[5]
doesn't exist as 5
is out of bounds (> 4
)
Upvotes: 1