原文: https://www.programiz.com/kotlin-programming/examples/print-integer
在此程序中,您将学习如何打印用户输入的整数。 整数存储在变量中,并分别使用nextInt()和println()函数打印到屏幕上。
示例 1:如何打印用户在 Kotlin 中使用扫描器输入的整数
import java.util.Scannerfun main(args: Array<String>) {// Creates a reader instance which takes// input from standard input - keyboardval reader = Scanner(System.`in`)print("Enter a number: ")// nextInt() reads the next integer from the keyboardvar integer:Int = reader.nextInt()// println() prints the following line to the output screenprintln("You entered: $integer")}
运行该程序时,输出为:
Enter a number: 10You entered: 10
在此示例中,创建了一个Scanner类的对象,即reader,它从keyboard(标准输入)获取用户的输入。
然后,nextInt()函数读取输入的整数,直到遇到换行符\n (Enter)为止。 然后将整数保存在类型为Int的变量integer中。
最后,println()函数使用字符串模板将integer打印到标准输出:计算机屏幕。
上面的程序与 Java 非常相似,没有样板类代码。 您可以在此处找到等效的 Java 代码:打印整数的 Java 程序
示例 2:如何在不使用扫描器的情况下打印整数
fun main(args: Array<String>) {print("Enter a number: ")// reads line from standard input - keyboard// and !! operator ensures the input is not nullval stringInput = readLine()!!// converts the string input to integervar integer:Int = stringInput.toInt()// println() prints the following line to the output screenprintln("You entered: $integer")}
运行该程序时,输出为:
Enter a number: 10You entered: 10
在上面的程序中,我们使用函数readLine()从键盘读取一行字符串。 由于readLine()也可以接受空值,因此!!运算符确保变量stringInput的值不为空。
然后,使用函数toInt()将存储在stringInput中的字符串转换为整数值,并存储在另一个变量integer中。
最后,使用println()将整数打印到输出屏幕上。
