Kotlin的print()、println()、readLine()、Scanner、REPL的功能在中国有以下选项: 打印()、打印并换行()、读取输入行()、扫描器()、交互式解释器()
今天我们将学习如何使用Kotlin的打印函数以及如何从控制台获取和解析用户输入。此外,我们还将介绍Kotlin REPL的使用。
Kotlin 打印函数
在屏幕上输出内容使用以下两种方法:
- print()
- println()
print语句将其内部的所有内容打印到屏幕上。println语句在输出末尾追加一个换行符。print语句在内部调用System.out.print。以下代码展示了print语句的示例。
fun main(args: Array<String>) {
var x = 5
print(x++)
println("Hello World")
print("Do dinasours still exist?\n")
print(false)
print("\nx is $x.")
println(" x Got Updated!!")
print("Is x equal to 6?: ${x == 6}\n")
}

转义字面量和表达式
为了逃避美元符号,并且将${expression}仅视为字符串而非计算式,我们可以对其进行转义处理。
fun main(args: Array<String>) {
val y = "\${2 == 5}"
println("y = ${y}")
println("Do we use $ to get variables in Python or PHP? Example: ${'$'}x and ${'$'}y")
val z = 5
var str = "$z"
println("z is $str")
str = "\$z"
println("str is $str")
}

打印函数的值
fun sumOfTwo(a: Int, b: Int) : Int{
return a + b
}
fun main(args: Array<String>) {
val a = 2
val b = 3
println("Value of ${'$'}a and ${'$'}b is : ${sumOfTwo(a,b)}")
println(println("Printing Value of ${'$'}a and ${'$'}b is : ${sumOfTwo(a,b)}"))
}

Kotlin 用户输入
要获取用户输入,可以使用以下两种方法:
- readLine()
- Scanner class
注意:用户输入需要使用命令行工具。您可以选择使用REPL或IntelliJ。我们在这里使用IntelliJ。
使用readLine()函数
“readLine()” 返回类型为String?的值,以处理读取文件末尾等出现的空值情况。下面的代码展示了使用readLine()的示例。
fun main(args: Array<String>) {
println("Enter your name:")
var name = readLine()
print("Length is ${name?.length}")
}
由于需要使用String类型的函数,我们需要对可空类型进行解包。只有当你绝对确定值不会为空时,才使用!!来强制将String?转换为String。否则,程序将会崩溃。将输入转换为整数,我们可以按照以下步骤进行:
fun main(args: Array<String>) {
var number = readLine()
try {
println("Number multiply by 5 is ${number?.toInt()?.times(5)}")
} catch (ex: NumberFormatException) {
println("Number not valid")
}
}
再次使用 ?. 运算符将可空类型转换为整数类型,使用 toInt()。然后我们将结果乘以5。持续读取输入 我们可以使用 do while 循环来持续读取输入,如下所示。
do {
line = readLine()
if (line == "quit") {
println("Closing Program")
break
}
println("Echo $line")
} while (true)
}

使用split操作符阅读多个值
我们可以通过分隔符来读取多个数值,并将它们保存在如下所示的元组形式中。
fun readIntegers(separator: Char = ',')
= readLine()!!.split(separator).map(String::toInt)
fun main(args: Array<String>) {
println("Enter your values:")
try {
val (a, b, c) = readLine()!!.split(' ')
println("Values are $a $b and $c")
} catch (ex: IndexOutOfBoundsException) {
println("Invalid. Missing values")
}
try {
val (x, y, z) = readIntegers()
println("x is $x y is $y z is $z")
} catch (ex: IndexOutOfBoundsException) {
println("Invalid. Missing values")
}
catch (ex: NumberFormatException) {
println("Number not valid")
}
}

val ints: List<String>? = readLine()?.split("|".toRegex())
println(ints)
Kotlin的Scanner类
为了接受输入,我们可以使用Scanner(System.`in`),它会从标准输入键盘接收输入。下面的代码演示了相同的功能:
要获取输入,可以使用Scanner(System.`in`)这个类从标准输入输入。以下代码展示了同样的功能。
fun main(args: Array<String>) {
val reader = Scanner(System.`in`)
print("Enter a number: ")
// nextInt() reads the next integer. next() reads the String
var integer:Int = reader.nextInt()
println("You entered: $integer")
reader.nextInt() 读取下一个整数。reader.next() 读取下一个字符串。reader.nextFloat() 读取下一个浮点数,依此类推。reader.nextLine() 将扫描器传递给下一行并清空缓冲区。以下代码展示了直接在打印语句中读取不同类型的输入。
import java.util.*
fun main(args: Array<String>) {
val reader = Scanner(System.`in`)
print("Enter a number: ")
try {
var integer: Int = reader.nextInt()
println("You entered: $integer")
} catch (ex: InputMismatchException) {
println("Enter valid number")
}
enterValues(reader)
//move scanner to next line else the buffered input would be read for the next here only.
reader.nextLine()
enterValues(reader)
}
fun enterValues(reader: Scanner) {
println("Enter a float/boolean :")
try {
print("Values: ${reader.nextFloat()}, ${reader.nextBoolean()}")
} catch (ex: InputMismatchException) {
println("First value should be a float, second should be a boolean. (Separated by enter key)")
}
}

Kotlin REPL的中文释义。
REPL也称为Read-Eval-Print-Loop,用于直接在交互式Shell中运行代码的一部分。我们可以通过启动Kotlin编译器来在终端/命令行中执行此操作。
安装命令行编译器
我们可以按照这里演示的方法,在Mac/Windows/Ubuntu上安装命令行编译器。通常,在Mac上,我们可以在终端使用HomeBrew来安装Kotlin编译器。
brew update
brew install kotlin
