Aman gautam :
I can't figure out a way to add values to an array in Kotlin .
I want to get values from user and add them to the array.
val arr = arrayOf<Int>()
or
var arr = intArrayOf()
In Java I would do something like this:
Scanner ob = new Scanner(System.in);
int arr[] = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i]=ob.nextInt();
}
How can I do the same in Kotlin?
holi-java :
You need to escape the static field in
of System
class with backtick (`), since in
is a keyword in Kotlin. for example:
val ob = Scanner(System.`in`)
You can create a fixed size int[]
array without initializing it immediately in Kotlin, then the default value of the elements in array are 0
. for example:
val arr = IntArray(5) // create IntArray via constructor
There is a bit different for using for-loop
in Kotlin, for example:
for(i in 0 until arr.size){
arr[i] = ob.nextInt();
}
OR initializing an int[]
array during creation, for example:
val arr = IntArray(5){ ob.nextInt() }
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=460696&siteId=1