luciferchase
luciferchase

Reputation: 559

How to print on the same line separated by space in Kotlin?

I am new to Kotlin and wondering if I could do this like in python it can be easily done by print("foo", end = "")

Here is my code:

fun main() {
    var first = 0
    var second = 1
    var third: Int

    for (i in 1..15){
        third = first + second
        println(third)
        first = second; second = third
    }
}

Upvotes: 0

Views: 2634

Answers (1)

CryptoFool
CryptoFool

Reputation: 23139

Use the print function instead of println to avoid printing a newline. Printing the space explicitly via a second call to print is one way to do the formatting you want. There are others, like using a format string, or converting the number you want to print to a string and concatenating on a space character or string containing a single space.

The main point is just that you want to use print over and over instead of println, and then use one println at the end to print a single newline when you're done.

fun main() {
    var first = 0
    var second = 1
    var third: Int

    for (i in 1..15){
        third = first + second
        print(third)
        print(' ')
        first = second; second = third
    }
    println()
}

Result:

1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 

Upvotes: 1

Related Questions