Kotlin print()、println()、readLine()、扫描仪、REPL

今天我们将学习如何使用Kotlin打印功能,以及如何从控制台获取和分析用户输入。

Kotlin 打印功能

要在屏幕上输出某些东西,使用以下两种方法:

  • 打印()
  • 打印()

印刷声明将其内部的所有内容打印到屏幕上。 println声明在输出的末尾附有新线条。 印刷声明内部称为System.out.print

 1fun main(args: Array<String>) {
 2var x = 5
 3print(x++)
 4println("Hello World")
 5print("Do dinasours still exist?\n")
 6print(false)
 7print("\nx is $x.")
 8println(" x Got Updated!!")
 9print("Is x equal to 6?: ${x == 6}\n")    
10}

To print a variable inside the print statement, we need to use the dollar symbol($) followed by the var/val name inside a double quoted string literal. To print the result of an expression we use ${ //expression goes here }. The output when the above code is run on the Kotlin Online Compiler is given below. kotlin print println functions

逃避字母和表达式

要逃避美元符号,假设把美元当作一个字符串,而不是计算它,我们可以逃避它。

 1fun main(args: Array<String>) {
 2val y = "\${2 == 5}"
 3println("y = ${y}")       
 4println("Do we use $ to get variables in Python or PHP? Example: ${'$'}x and ${'$'}y")
 5val z = 5
 6var str = "$z"
 7println("z is $str")
 8str = "\$z"
 9println("str is $str")
10}

kotlin print statements escaping literals Note a simple $ without any expression/variable set against it implicitly escapes it and treats it as a part of the string only.

印刷函数值

 1fun sumOfTwo(a: Int, b: Int) : Int{
 2    return a + b
 3}
 4
 5fun main(args: Array<String>) {
 6val a = 2
 7val b = 3
 8println("Value of ${'$'}a and ${'$'}b is : ${sumOfTwo(a,b)}") 
 9println(println("Printing Value of ${'$'}a and ${'$'}b is : ${sumOfTwo(a,b)}"))    
10}

The following output is printed: kotlin print statements printing functions Note: Passing a print inside another behaves like recursion. The innermost is printed first. print statement returns a Unit (equivalent of void in Java).

Kotlin 用户输入

为了获取用户输入,可以使用以下两种方法:

  • readLine()
  • [扫描器]( / 社区 / 教程 / 扫描器类 - 在 Java) 类

注意:用户输入需要命令行工具. 您可以使用 REPL 或 IntelliJ. 让我们在这里使用 IntelliJ。

使用 readLine( )

readLine() 返回 String? 类型的值,以处理当您阅读文件的结尾等时可能发生的 null 值。

1fun main(args: Array<String>) {
2    println("Enter your name:")
3    var name = readLine()
4    print("Length is ${name?.length}")
5}

正如您所看到的,我们需要解除可重置类型,以便在属性上使用 String 类型函数。 使用 a!! 强迫将 String? 转换为 String,只有当您绝对确定该值不会为 null 否则它会崩溃。 ** 将输入转换为整数** 要将输入 String 转换为 Int,我们会做以下操作:

1fun main(args: Array<String>) {
2var number = readLine()
3try {
4        println("Number multiply by 5 is ${number?.toInt()?.times(5)}")
5    } catch (ex: NumberFormatException) {
6        println("Number not valid")
7    }
8}

再次,我们使用 ?. 运算器将可重置类型转换为使用 toInt() 的 Int。 然后我们将其乘以 5. ** 连续阅读输入** 我们可以使用 do while loop 以连续阅读输入,如下所示。

 1do {
 2        line = readLine()
 3
 4        if (line == "quit") {
 5            println("Closing Program")
 6            break
 7        }
 8
 9        println("Echo $line")
10
11    } while (true)
12}

The output of the above in the IntelliJ Command Line is given below. kotlin print statements loop

使用 split 运算器读取多个值

我们可以读取由界限分开的多个值,并将其保存为下图所示的tuple形式。

 1fun readIntegers(separator: Char = ',')
 2        = readLine()!!.split(separator).map(String::toInt)
 3
 4fun main(args: Array<String>) {
 5    println("Enter your values:")
 6    try {
 7        val (a, b, c) = readLine()!!.split(' ')
 8        println("Values are $a $b and $c")
 9    } catch (ex: IndexOutOfBoundsException) {
10        println("Invalid. Missing values")
11    }
12
13    try {
14        val (x, y, z) = readIntegers()
15        println("x is $x y is $y z is $z")
16    } catch (ex: IndexOutOfBoundsException) {
17        println("Invalid. Missing values")
18    }
19    catch (ex: NumberFormatException) {
20        println("Number not valid")
21    }
22
23}

The split function takes in the character that'll be the delimiter. readIntegers() function uses a map on a split to convert each value to an Int. If you enter values lesser than the specified in the tuple, you'll get an IndexOutOfBoundsException. We've used try-catch in both the inputs. The output looks like this: kotlin print statements split and exceptions Alternatively, instead of tuples, we can use a list too as shown below.

1val ints: List<String>? = readLine()?.split("|".toRegex())
2println(ints)

科特林扫描仪类

要获取输入,我们可以使用扫描器(System.in)从标准输入键盘获取输入。

1fun main(args: Array<String>) {
2    val reader = Scanner(System.`in`)
3    print("Enter a number: ")
4
5    // nextInt() reads the next integer. next() reads the String
6    var integer:Int = reader.nextInt()
7
8    println("You entered: $integer")

reader.nextInt() 读取下一个整数. reader.next() 读取下一个字符串. reader.nextFloat() 读取下一个字符串等等. reader.nextLine() 将扫描仪传输到 nextLine,并清除缓冲器。

 1import java.util.*
 2
 3fun main(args: Array<String>) {
 4
 5    val reader = Scanner(System.`in`)
 6    print("Enter a number: ")
 7
 8    try {
 9        var integer: Int = reader.nextInt()
10        println("You entered: $integer")
11    } catch (ex: InputMismatchException) {
12        println("Enter valid number")
13    }
14    enterValues(reader)
15    //move scanner to next line else the buffered input would be read for the next here only.
16    reader.nextLine()
17    enterValues(reader)
18}
19
20fun enterValues(reader: Scanner) {
21    println("Enter a float/boolean :")
22    try {
23        print("Values: ${reader.nextFloat()}, ${reader.nextBoolean()}")
24    } catch (ex: InputMismatchException) {
25        println("First value should be a float, second should be a boolean. (Separated by enter key)")
26    }
27}

InputMismatchException is thrown when the input is of a different type from the one asked. The output is given below. kotlin scanner class

卡特勒 Repl

REPL 也被称为读-Eval-Print-Loop 用于直接在交互式壳中运行代码的一部分,W e 可以通过启动 kotlin 编译器在我们的终端/命令行中执行。

安装命令行编译器

我们可以在Mac/Windows/Ubuntu上安装命令行编译器,如下所示(https://kotlinlang.org/docs/tutorials/command-line.html).通常在Mac上,我们可以在我们的终端上使用HomeBrew来安装Kotlin编译器。

1brew update
2brew install kotlin

Once it is done, start the REPL by entering kotlinc in your terminal/cmd Following is my first code in the REPL. kotlin REPL That's all for Kotlin print functions and quick introduction of Kotlin REPL.

Published At
Categories with 技术
Tagged with
comments powered by Disqus