简体   繁体   中英

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
    }
}

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM