Reputation: 25
Im starting to learn Kotlin and wanted to try a little code, just to read and print an int array from the user, this is my code
import java.util.*
fun main(){
val scan = Scanner(System.`in`)
println("Enter the number of elements: ")
var arrayInt = IntArray(scan.nextInt())
println("Size of the array: ${arrayInt.size}")
println("Enter the numbers: ")
for(item in arrayInt)
arrayInt[item] = scan.nextInt()
for(i in arrayInt)
print("${arrayInt[i]} ")
}
but when I run the code the only thing i get print is the last number I enter and some 0s, what im doing wrong? thanks
Upvotes: 1
Views: 3117
Reputation: 1
To ask for user input for the size of Array and Insert Elements use this:
println("Enter Size of Array: ")
val aSize = Integer.valueOf(readln())
*//Muhammad Salman*
var arrayInt = IntArray(aSize)
println("Enter Array Elements: (Numbers Only)")
for (i in 0 until aSize){
arrayInt[i] = Integer.valueOf(readln())
}
*// Muhammad Salman*
println("\nElements in Array: ")
for (x in 0 until aSize){
print("" + arrayInt[x] + " ")
}
Upvotes: 0
Reputation: 91
you can use something like
val scan = Scanner(System.`in`)
println("Enter the number:")
val n = scan.nextLine().trim().toInt()
println("Enter array:")
val arr = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray()
println(Arrays.toString(arr))
Upvotes: 1
Reputation: 65
fun main()
{
val arraya = arrayOf(1, 2, 3, 4, 5)
for (i in 0..arrayname.size-1)
{
print(" "+arraya[i])
}
println()
val arrayname2 = arrayOf<Int>(10, 20, 30, 40, 50)
for (i in 0..arrayname2.size-1)
{
print(" "+arrayname2[i])
}
}
Pretty sure that is how you do it
Upvotes: 1
Reputation: 13424
The incorrect part of your code is this:
for(item in arrayInt)
arrayInt[item] = scan.nextInt()
Here, item
is not an index. It is a value from arrayInt
. It means that, if the array was just constructed, every item
will be 0
, which is the default Int
value. Thus, what you are doing is basically:
arrayInt[0] = scan.nextInt()
arrayInt.size
times.
I would suggest dropping Scanner
entirely for such trivial task and stick with Kotlin's richer library:
fun main() {
print("Please input numbers separated by spaces: ")
val list = readLine()!!.split(" ").map { it.toInt() }
println(list)
}
readLine()
will read the entire line, and may return null
if it reaches the end-of-file as a first character. However, it won't, because we are not planning to input it - we use !!
to tell the compiler that it will be a valid String
, not a String?
which may be null
. Then we split()
on spaces, which will yield a List<String>
and we map()
every String
to Int
via toInt()
method.
After all, we end up with list
value which contains inputted numbers.
Upvotes: 1
Reputation: 93571
When you use
for(i in arrayInt)
instead of
for (i in arrayInt.indices)
or
for (i in 0 until arrayInt.size)
then the i
is the actual content of the array, not the array indices.
So in your case, your last line can be changed to
print("$i ")
Upvotes: 2