0

How to enter a value in kotlin and have it added 10 times and then divided into 10 using a flow (while) control.

This is my code:

calcular.setOnClickListener {

            if (et_valor.text.isEmpty())
                Toast.makeText(this, "Debe ingresar un valor", Toast.LENGTH_SHORT).show()

            val valor = et_valor.text.toString().toInt()

            var x = 0

            val suma = 0

            while (x < 10) {

              val suma2 = suma+valor

              val division = suma2/10

              x++

              tv_resultad.text=("La sema del numero es $suma2 y la division es $division");tv_resultad.text.toString().plus(x)

            }
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436

3 Answers3

0

Try this

if (et_valor.text.isEmpty())
    Toast.makeText(this, "Debe ingresar un valor", Toast.LENGTH_SHORT).show()

    val valor = et_valor.text.toString().toInt()

    var x = 0

    val suma = 0

    while (x < 10) {
      val suma2 = suma+valor
        x++
    }

    val division = suma2/10
    tv_resultad.text=("La sema del numero es $suma2 y la division es $division")
    tv_resultad.text.toString().plus(x)
Atiq
  • 14,435
  • 6
  • 54
  • 69
0

You can try this out, if the et_valor is not is empty, it will display the toast, if not it will go in the loop and keep adding valor every time and showing its value and the value of the cumulative value divided by 10. You can also initialize division before the while loop but it won't make a difference.

    if (!et_valor.text.isEmpty()){
        val valor = et_valor.text.toString().toInt()

        var x = 0

        var suma = 0

        while (x < 10) {

            suma += valor

            val division = suma/10

            x++

            tv_resultad.text=("La sema del numero es $suma y la division es $division");
            tv_resultad.text.toString().plus(x)
        }

    } else {
        Toast.makeText(this, "Debe ingresar un valor", Toast.LENGTH_SHORT).show()
    }
0

another way

calcular.setOnClickListener {
        et_valor.text.toString().toIntOrNull()?.let { value ->
            calculate(value) { result, times ->
                tv_resultad.text =
                    ("La sema del numero es $result y la division es $value ").plus(times)
            }
        } ?: Toast.makeText(this, "Debe ingresar un valor", Toast.LENGTH_SHORT).show()
    }

    fun calculate(
        value: Int,
        times: Int = 10,
        onComplete: (result: String, times: String) -> Unit
    ) {
        var x = times
        var result = 0
        while (x > 0) {
            result += value
            x--
        }
        onComplete(result.toString(), times.toString())
    }