Standard input
To read from the standard input, Java provides the Scanner
class. Kotlin offers two main ways to read from the standard input: the Scanner
class, similar to Java, and the readln()
function.
Read from the standard input with Java Scanner
In Java, the standard input is typically accessed through the System.in
object. You need to import the Scanner
class, create an object, and use methods like .nextLine()
and .nextInt()
to read different data types:
Use Java Scanner in Kotlin
Due to Kotlin's interoperability with Java libraries, you can access Java Scanner from Kotlin code out of the box.
To use Java Scanner in Kotlin, you need to import the Scanner
class and initialize it by passing a System.in
object that represents the standard input stream and dictates how to read the data. You can use the available reading methods for reading values different from strings, such as .nextLine()
, .next()
, and .nextInt()
:
Other useful methods for reading input with Java Scanner are .hasNext()
, .useDelimiter()
, and .close()
:
The
.hasNext()
method checks if there's more data available in the input. It returns the boolean valuetrue
if there are remaining elements to iterate andfalse
if no more elements are left in the input.The
.useDelimiter()
method sets the delimiter for reading input elements. The delimiter is whitespaces by default, but you can specify other characters. For example,.useDelimiter(",")
reads the input elements separated by commas.The
.close()
method closes the input stream associated with the Scanner, preventing further use of the Scanner for reading input.
Read from the standard input with readln()
In Kotlin, apart from the Java Scanner, you have the readln()
function. It is the most straightforward way to read input. This function reads a line of text from the standard input and returns it as a string:
For more information, see Read standard input.