Skip to content Skip to sidebar Skip to footer

How Not To Repeat Math Operations Two Times In Calculator App?

I have made a simple calculator in 'Kotlin' using an android studio the problem I got and I don't have a way to fix it is how not to repeat the math operations after typing a numbe

Solution 1:

If You don't want to add two operators next to each other You have to check if last character is the operator. It will look something like this:

fun appendOnExpresstion(string: String, canClear: Boolean)
{
    if (tvResult.text.isNotEmpty())
    {
        tvExpression.text = ""
    }
    if (canClear)
    {
        tvResult.text = ""
        tvExpression.append(string)
    }
    else
    {
        if (tvExpression.text.lastOrNull() !in arrayOf('+', '-', '*', '/')) // You are adding operator so You have to check if last char is oparetor
        {
            tvExpression.append(tvResult.text)
            tvExpression.append(string)
        }
        tvResult.text = ""
    }
}

Solution 2:

You can use this:

first param: it is the String that is pass

second param: it is the number of time that reapeat something characters

fun removeConsecutiveCharactersInString(str: String, maxConsecutiveAllowedCount: Int)
{
val builder = StringBuilder(str)

var i = 0

while (i < builder.length) {

    var foundCount = 0

    for (j in i - 1 downTo 0) {

        if (lowerCasedChar(builder[i]) == lowerCasedChar(builder[j])) {

            foundCount++

            if (foundCount >= maxConsecutiveAllowedCount) {

                builder.deleteCharAt(i)

                i--

                break

            }
        } else {

            break

        }
    }

    i++
}

return builder.toString()

}


Post a Comment for "How Not To Repeat Math Operations Two Times In Calculator App?"