-2

I am trying to have a text-box populate with X if another text-box has a certain value, else Y. However, it's populating with X or Y seemingly randomly. d4 is my button, d4result is where it populates the result, d4txt1 is where I want to see a 1 or 0, depending.

d4.setOnClickListener {
        if  (d4result.text.toString() == "1") {
            d4txt1.text = "1"
        } else {
            d4txt1.text = "0"
        }
        val rand = Random().nextInt(4) + 1
        d4result.text = rand.toString()
    }

So if d4result is populated with 1, I want d4txt1 to populate with 1, otherwise it should be zero. But when I try it, I get 1 or 0 and I can't notice a pattern as to when/why.

2 Answers2

-1

Use equals instead of ==. == operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.

d4.setOnClickListener {
        if  (d4result.text.toString().equalsIgnoreCase("1")) {
            d4txt1.text = "1"
        } else {
            d4txt1.text = "0"
        }
        val rand = Random().nextInt(4) + 1
        d4result.text = rand.toString()
    }
Muazzam A.
  • 647
  • 5
  • 17
-2

Java is tricky about that. The == operator compares the two object pointers, not their values. It's fine for integers and floats but almost never useful for strings.

Instead use the .equals() method or the .equalsIgnoreCase() method:

if (d4result.text.toString().equalsIgnoreCase("1")) { ...
Jerry101
  • 12,157
  • 5
  • 44
  • 63