English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在该程序中,您将学习如何打印用户输入的整数。整数存储在变量中,并分别使用nextInt()和println()函数打印到屏幕上。
import java.util.Scanner fun main(args: Array<String>) { //创建一个读取器实例,该实例将 //从标准输入-键盘输入 val reader = Scanner(System.`in`) print("Enter a number: ") //nextInt()从键盘读取下一个整数 var integer:Int = reader.nextInt() //The println() function prints the following line to the output screen println("You entered: $integer") }
When running the program, the output is:
Enter a number: 10 You entered: 10
在此示例中,Scanner 创建了一个类对象,该对象reader从keyboard (标准输入)中获取用户的输入。
然后,nextInt()函数读取输入的整数,直到遇到换行符\n (Enter)。然后将整数保存在integer类型为的变量中Int。
最后,println()函数将打印integer到标准输出:使用字符串模板的计算机屏幕。
上面的程序与Java非常相似,没有样板类代码。您可以在此处找到等效的Java代码:Java program to print an integer
fun main(args: Array<String>) { print("Enter a number: ") //Read a line from the standard input keyboard //The !! operator ensures that the input is not empty val stringInput = readLine()!! //Convert the string input to an integer. var integer: Int = stringInput.toInt() // The println() function prints the following line to the output screen println("You entered: $integer") }
When running the program, the output is:
Enter a number: 10 You entered: 10
In the above program, we use the function readLine() to read a line of string from the keyboard. Since readLine() can also accept null, soNot operatorEnsure that the non-null value stringInput is in variable.
Then, use the function toInt() to convert the string stored in stringInput to an integer value and store it in another variable integer.
Finally, use the println() function to print the integer to the output screen.