Skip to main content
Logo image

Problem Solving with Algorithms and Data Structures using Kotlin The Interactive Edition

Section 1.11 Input and Output

We often have a need to interact with users, either to get data or to provide some sort of result.

Subsection 1.11.1 Input

Most programs today use a dialog box as a way of asking the user to provide some type of input. While Kotlin does have a way to create dialog boxes, there is a much simpler function that we can use. Kotlin provides us with a function that allows us to ask a user to enter some data and returns a reference to the data in the form of a string. The function is called readln.
Listingย 1.11.1 shows an example of this: it asks the user for their age in years and prints the approximate age in days:
Listing 1.11.1. Age in Days Program
fun main() {
    print("Enter your age in years: ")
    val years = readln().toInt()
    val days = years * 365
    println("Your age in days is approximately $days.")
}
It is important to note that the value returned from the readln function will be a string representing the exact characters that were entered after the prompt. If you want this string interpreted as another type, you must provide the type conversion explicitly. The above program uses the toInt method on strings to an integer.
Enter your age in years: 27
Your age in days is approximately 9855.

Subsection 1.11.2 String Templates

One way in which Kotlin makes output easier is through using string templates. String templates arenโ€™t only used for output --- theyโ€™re really just a feature of strings --- but we will commonly use them in this book for output purposes. Listingย 1.11.1 above uses a string template near the end of line 5, where is uses the expression $days as part of the string being printed. In Kotlin, a variable name inside a string that has a $ in front of it is a string template, which means that it is evaluated as an expression. In other words, $days appearing in that string indicates that Kotlin should replace $days with the value of the variable days.
String templates can also be used to contain more complicated expressions if they are placed in curly braces. Here are some examples:
fun main() {
    val animal = "gazelle"
    val age = 20
    println("Our friend $animal is $age years old.")
    println("The animal string has ${animal.count()} characters in it.")
    println("In a few years, the animal will be ${age+3} years old.")
}
Here is the program output:
Our friend gazelle is 20 years old.
The animal string has 7 characters in it.
In a few years, the animal will be 23 years old.

Subsection 1.11.3 String Formatting

We have already seen that the println function provides a very simple way to output values from a Kotlin program. We can also the print function, which does not automatically print a newline at the end of the string. This allows us to be able to print multiple strings on the same line, as shown in the following example:
fun main() {
    print("Hello")
    print("***")
    println("World")
}
While we can use print(), println(), and string templates for output, it often gives us output that is less than pleasing, as in Listingย 1.11.2.
Listing 1.11.2. Discount program
fun main() {
    val discountRate = 0.0725

    print("Enter price: $")
    val price = readln().toDouble()

    val newPrice = price * (1.0 - discountRate)
    println("Your new price is $$newPrice.")
}
Notice the double $ in line 8 above. The first $ is there to simply print a $. The second $ is part of the string template $newPrice, which obtains a string representation of the variable newPrice.
Here is the output:
Enter price: $12.95
Your new price is $12.011125.
That new price is ugly: we typically show dollars and cents with two decimal places only.
It is often useful to have more control over the look of your output. Fortunately, Kotlin provides us with an alternative called string formatting. The String.format() method as its first argument a format stringโ€” a template in which words or spaces that will remain constant are combined with placeholders for variables that will be inserted into the string. Letโ€™s expand on our โ€œage in daysโ€ program to ask the userโ€™s name:
Listing 1.11.3. Name and Age
fun main() {
    print("Enter your name: ")
    val name = readln()

    print("Enter your age in years: ")
    val years = readln().toInt()

    val days = years * 365
    println(String.format("You are about %d days old, %s.",
            days, name))
}
Letโ€™s examine lines 9 and 10. The first argument to String.format() is the format string. The %d and %s are format specifiers; you can think of them as placeholders for values. The %d specifier says that the placeholder will be filled in by a decimal integer value; %s is a placeholder for a String value.
The remaining arguments to String.format() are the values that will fill in the %d and %s placeholders. The values are taken in order from left to right and inserted into the format string. Hereโ€™s what the output looks like:
Enter your name: Kim
Enter your age in years: 29
You are about 10585 days old, Kim.
The format string may contain one or more conversion specifications. A conversion character tells the format operator what type of value is going to be inserted into that position in the string. In the example above, the s specifies a string, while the d specifies an integer. Other possible type specifications include f, e, g, c, or %. Tableย 1.11.4 summarizes all of the various type specifications.
Table 1.11.4. String Formatting Conversion Characters
Character Output Format
d Integer
u Unsigned integer
f Floating point (default six decimal places if needed)
e Floating point as exponential notation: m.dddddde+/-xx
E Floating point as exponential notation: m.ddddddE+/-xx
g Use %e for exponents less than \(-4\) or greater than \(+5\text{,}\) otherwise use %f
c Single character
s String
% Insert a literal % character
n Insert a newline character
In addition to the format character, you can also include a format modifier between the % and the format character. Format modifiers can be used to specify the field width along with a number of digits after the decimal point. Tableย 1.11.5 explains these format modifiers.
Table 1.11.5. Additional formatting options
Modifier Example Description
number %20d Put the value in a field width of 20
- %-20d Put the value in a field 20 characters wide, left-justified
+ %20d Put the value in a field 20 characters wide, right-justified
0 %020d Put the value in a field 20 characters wide, fill in with leading zeros
. %20.2f Put the value in a field 20 characters wide with 2 characters to the right of the decimal point
Listingย 1.11.6 gives some examples of String.format().
Listing 1.11.6. Examples of Formatted Output
The width given in the example is the minimum space allocated for the output. If output requires more space, as in the last line, it will use more.
Here is the output:
|Kotlin|
|    Kotlin|
|Kotlin    |

|123456|
|    123456|
|123456    |
|   123,456|

|12345.678901|
| 12345.679|
|12,345.679|
| 1.235e+04|
|12345.6789012|
This program also gives examples of how to write a comment in Kotlin. The characters // introduce a single-line comment; Kotlin ignores everything from the // to the end of line (lines 11, 12, and 14). Multi-line coments begin with /* and end with */ (lines 6-9). The additional * at the beginning of each line inside the multiline comment (lines 7 and 8) are a common stylistic addition to make the comment easier to read, but those asterisks on line 7 and 8 are not required.
You have attempted of activities on this page.