示例 1:如何在 Kotlin 中使用 Scanner 打印用户输入的整数
import java.util.Scanner
fun main(args: Array<String>) {
// Creates a reader instance which takes
// input from standard input - keyboard
val reader = Scanner(System.`in`)
print("Enter a number: ")
// nextInt() reads the next integer from the keyboard
var integer:Int = reader.nextInt()
// println() prints the following line to the output screen
println("You entered: $integer")
}
输出:
Enter a number: 10 You entered: 10
在此示例中,创建了 `Scanner` 类的对象 `reader`,它从 `keyboard`(标准输入)获取用户输入。
然后,`nextInt()` 函数读取用户输入的整数,直到遇到换行符 `\n (Enter)`。该整数随后被保存在类型为 `Int` 的变量 `integer` 中。
最后,`println()` 函数使用字符串模板将 `integer` 打印到标准输出:电脑屏幕。
上述程序与 Java 非常相似,只是缺少样板类代码。您可以在此处找到等效的 Java 代码:Java 程序打印整数
示例 2:如何在不使用 Scanner 的情况下打印整数
fun main(args: Array<String>) {
print("Enter a number: ")
// reads line from standard input - keyboard
// and !! operator ensures the input is not null
val stringInput = readLine()!!
// converts the string input to integer
var integer:Int = stringInput.toInt()
// println() prints the following line to the output screen
println("You entered: $integer")
}
输出:
Enter a number: 10 You entered: 10
在上述程序中,我们使用 `readLine()` 函数从键盘读取一整行字符串。由于 `readLine()` 也可以接受 null 值,因此 `!!` 操作符确保了变量 `stringInput` 的值非空。
然后,`stringInput` 中存储的字符串使用 `toInt()` 函数转换为整数值,并保存在另一个变量 `integer` 中。
最后,使用 `println()` 将整数打印到输出屏幕。