这一期是关于数组和循环的练习题:
第一题是这样的:
val array = // initalize array here(在这里填空)
val sizes = arrayOf("byte","kilobyte","megabyte","gigabyte","terabyte","petabyte","exabyte")
for((i, value) in array.withIndex())
{
println("1${sizes[i]}=${value.toLong()}bytes")
}
要求输出是这样的:
1 byte =1 bytes
1 kilobyte =1000 bytes
1 megabyte =1000000 bytes
1 gigabyte =1000000000 bytes
1 terabyte =1000000000000 bytes
1 petabyte =1000000000000000 bytes
1 exabyte =1000000000000000000 bytes
正确答案是:
val array = Array(7){1000.0.pow(it)}
注意:这里使用的是1000.0而不是1000
下一题是关于immutable的多选题,其中immutable意味着不能改变can not change:
题目不好复制 。所以截了图(包含正确答案):
最后是一道编程题:
Basic example
Create an integer array of numbers callednumbers, from 11 to 15.
Create an empty mutable list for Strings.
Write aforloop that loops over the array and adds the string representation of each number to the list.
Challenge example
How can you use aforloop to create (a list of) the numbers between 1 and 100 that are divisible by 7?
答案是(基础例题没有给答案,答案是我自己写的):
val numbers = intArrayOf(11,12,13,14,15)var list :MutableList = mutableListOf()
for(number in numbers){
list.add(number.toString())
}
下面的挑战例题,官方答案有两个,分别是:
var list3 : MutableList = mutableListOf()
for(i in 0..100 step 7) list3.add(i)
print(list3)
或者:
for(i in 0..100 step 7) println(i.toString()+" - ")
需要注意的是:mutable是可变列表,包含了添加删除等方法