美文网首页我爱编程
2、Kotlin基础(练习题)

2、Kotlin基础(练习题)

作者: 北方素素 | 来源:发表于2018-06-19 20:02 被阅读0次

那么下面是第一道练习题:

When it comes to basic operations, it's a good thing for this to become

automatic, something less to think about while you are trying to figure

out the solution to your actual programming challenge. There is only one

road to automaticity, and that's practice. The following are some

starting points for playing in REPL with the operations and concepts

introduced in this lesson.

这是一道十分简单的算术题:

官方答案是:2.plus(71).plus(233).minus(13).div(30).plus(1)

第二题:

Create a String variable rainbowColor, set its color value, then change it.

Create a variable blackColor whose value cannot be changed once assigned. Try changing it anyway.

这道题主要让大家巩固一下变量和常量,前者可以修改,后者不可修改

官方答案是:

var rainbowColor ="red"

rainbowColor ="blue"

val blackColor ="black"

blackColor ="white"// Error

第三题:

Try to setrainbowColortonull. Declare two variables,greenColorandblueColor. Use two different ways of setting them tonull.

这是一道关于null的问题,知识点是?这个符号

官方答案是:

var greenColor =null

var blueColor: Int? =null

第四题:

Create a list with two elements that are null; do it in two different ways.

Next, create a list where the list is null.

这道题主要是练习之前讲过的空list,包括列表可以为null,列表元素可以为null

官方答案是:

listOf(null,null)

[null,null]

var list: List<Int?> = listOf(null, null)

var list2:List<Int>? =null

第五题:

Create a nullable integer variable callednullTest, and set it tonull. Use a null-check that increases the value by one if it's not null, otherwise returns 0, and prints the result.

这道题想考察我们对于null类型的检查,要求我们使用Elvis operator.,也就是? ?:

官方答案是:

println(nullTest2?.inc()?:0)

相关文章

网友评论

    本文标题:2、Kotlin基础(练习题)

    本文链接:https://www.haomeiwen.com/subject/gqdzeftx.html