how to use scanner in kotlin
To use the Scanner
class in Kotlin, you can follow these steps:
Step 1: Import the Scanner
class
At the beginning of your Kotlin file, import the Scanner
class from the java.util
package. This will allow you to use the Scanner
class in your code.
import java.util.Scanner
Step 2: Create a Scanner
object
Next, create an instance of the Scanner
class by calling its constructor. You can pass the standard input stream (System.in
) as an argument to the constructor. This will allow you to read input from the user.
val scanner = Scanner(System.`in`)
Step 3: Read input from the user
You can use various methods provided by the Scanner
class to read different types of input from the user. For example, you can use the nextLine()
method to read a line of text, the nextInt()
method to read an integer, or the nextDouble()
method to read a floating-point number.
Here's an example that reads a line of text from the user:
println("Enter your name:")
val name = scanner.nextLine()
println("Hello, $name!")
In this example, the nextLine()
method is used to read a line of text entered by the user and store it in the name
variable. The entered name is then printed with a greeting message.
Step 4: Close the Scanner
object
After you have finished using the Scanner
object, it's good practice to close it to release any system resources associated with it. You can call the close()
method on the Scanner
object to do this.
scanner.close()
Closing the Scanner
object is not mandatory, but it's recommended to prevent resource leaks.
That's it! You have now learned how to use the Scanner
class in Kotlin to read input from the user.