简体   繁体   中英

How to create and print an array from user in Kotlin

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

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 ")
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

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.

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))

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] + " ")
    
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM