Home > OS >  Kotlin - Readln() gets only first word in string
Kotlin - Readln() gets only first word in string

Time:10-14

I'm making a first project "Flashcards" for Kotlin course and faced with unexpected program behavior. Function "readln()" gets only first word in sting (separetad by space " "). What is a problem, what do you think? Note: fun "reading" needed and for now I can realize it in this way only. Regular "readln()" have same problem. Code below.

import java.util.*

var logText: String = ""
fun println(text: String = "") {
    kotlin.io.println(text)
    logText  = text   "\n"
}
fun reading(): String {
    val scan = Scanner(System.`in`)
    val text = scan.next()
    logText  = text   "\n"
    return text
}

fun adding(addCard: MutableMap<String, String>): MutableMap<String, String> {
    val definition: String
    println("The card:")
    val card: String = reading()
    if (card in addCard.keys) {
        println("The card \"$card\" already exists.")
        return addCard
    } else {
        println("The definition of the card:")
        definition = reading()
        if (definition in addCard.values) {
            println("The definition \"$definition\" already exists.")
            return addCard
        }
    }
    addCard[card] = definition
    println("The pair (\"${card}\":\"${definition}\") has been added.")
    return addCard
}

fun main() {
    val actionList = mutableListOf("add", "exit")
    var action = ""
    val cards = mutableMapOf<String, String>()
    while (action != "exit") {
        println("Input the action (add, remove, exit):")
        action = reading()
        if (action !in actionList) {
            println("Wrong action!")
            continue
        } else {
            when (action) {
                "add" -> cards.putAll(adding(cards))
                /* "remove" -> println("Not supported.")
                "import" -> println("Not supported.")
                "export" -> println("Not supported.")
                "ask" -> println("Not supported.")
                "log" -> println("Not supported.")
                "hardest card" -> println("Not supported.")
                "reset stats" -> println("Not supported.") */
            }
        }
    }
    println("Bye bye!")
}

CodePudding user response:

You're not using readln() in your code, you're using a Scanner with the next() function and no delimiter set. So by default, that just splits on words:

import java.util.Scanner

fun main() {
    val input = "here are some words"
    val scanner = Scanner(input)
    while(scanner.hasNext()) {
        println(scanner.next())
    }
}
here
are
some
words

If you use scanner.nextLine() then it'll read the whole line as a token, and that's basically the behaviour of readln() as well. If readln() is giving you individual words, you'll have to post the code that's doing that, because it'll be something else going on

  • Related