原文: https://www.programiz.com/kotlin-programming/examples/print-integer

在此程序中,您将学习如何打印用户输入的整数。 整数存储在变量中,并分别使用nextInt()println()函数打印到屏幕上。

示例 1:如何打印用户在 Kotlin 中使用扫描器输入的整数

  1. import java.util.Scanner
  2. fun main(args: Array<String>) {
  3. // Creates a reader instance which takes
  4. // input from standard input - keyboard
  5. val reader = Scanner(System.`in`)
  6. print("Enter a number: ")
  7. // nextInt() reads the next integer from the keyboard
  8. var integer:Int = reader.nextInt()
  9. // println() prints the following line to the output screen
  10. println("You entered: $integer")
  11. }

运行该程序时,输出为:

  1. Enter a number: 10
  2. You entered: 10

在此示例中,创建了一个Scanner类的对象,即reader,它从keyboard(标准输入)获取用户的输入。

然后,nextInt()函数读取输入的整数,直到遇到换行符\n (Enter)为止。 然后将整数保存在类型为Int的变量integer中。

最后,println()函数使用字符串模板将integer打印到标准输出:计算机屏幕。


上面的程序与 Java 非常相似,没有样板类代码。 您可以在此处找到等效的 Java 代码:打印整数的 Java 程序


示例 2:如何在不使用扫描器的情况下打印整数

  1. fun main(args: Array<String>) {
  2. print("Enter a number: ")
  3. // reads line from standard input - keyboard
  4. // and !! operator ensures the input is not null
  5. val stringInput = readLine()!!
  6. // converts the string input to integer
  7. var integer:Int = stringInput.toInt()
  8. // println() prints the following line to the output screen
  9. println("You entered: $integer")
  10. }

运行该程序时,输出为:

  1. Enter a number: 10
  2. You entered: 10

在上面的程序中,我们使用函数readLine()从键盘读取一行字符串。 由于readLine()也可以接受空值,因此!!运算符确保变量stringInput的值不为空。

然后,使用函数toInt()将存储在stringInput中的字符串转换为整数值,并存储在另一个变量integer中。

最后,使用println()将整数打印到输出屏幕上。