Setting a User Input to a Double (Or a Specific Data Type)


#1

Hi Everyone, I am pretty new to Kotlin, but I have already identified a project that I want to work on. The first step involves me rewriting a C# console app in Kotlin. The following code yields the error below (For the sake of being concise, assume I already have this code in a main function):

var originalTotal = readLine()
var tip = .15
println(“Your tip is: ${originalTotal.toDouble() * tip}”)
var total = originalTotal.toDouble() + (originalTotal.toDouble() * tip)
println(“Your total is $total”)

Error:(16, 42) Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?

If I explicitily assign a number to originalTotal, this works fine. However, it errors out when I assign originalTotal to a user input. Is there a way I can convert the user’s input to a Double?

Thanks in advance and well wishes.

John


#2

Try this instead which checks that what you’re entering is a valid number and, if it isn’t, asks you to reinput it:

    var originalTotal: Double?

    do {
       print("Enter the original total : ")
       originalTotal  = readLine()!!.toDoubleOrNull()
       if (originalTotal == null) println("Not a valid number, try again")
    }
    while (originalTotal == null)

    var tip = 0.15 * originalTotal
    println("Your tip is : $tip")
    var total = originalTotal + tip
    println("Your total is : $total")

Checking for valid entries
#3

Incidentally, if the variables 'tip' and 'total' won’t be changed again after these calculations, I’d declare them as 'val' rather than 'var'.


#4

This is interesting. The tip will always be a .15, so I probably should use val. However, I want to be able to iterate this whole application if requested (I haven’t gotten to testing that code yet). Shouldn’t I change JUST the tip to a val and leave the original total to a var?


#5

Thank you! This makes more sense. Per your suggestion, I will change the tip to a val.