Conditionals bugged on Android Studio with Kotlin

Issue

I am teaching a simple comparisons on programming, but I have found something odd when I am trying to list all the natural numbers below 10 that are multiples of 3 or 5, when I add the following conditions the number 0 is added, even when specifically is conditional to add numbers if they are different from 0, I have already made invalidate caches and restart to Android Studio. Am I missing something here? Below is the code

 fun multiplesOf() {
        val arrayOfSelected: ArrayList<Int> = arrayListOf()

        for (i in 0..10) {
            if (i != 0 && i % 3 == 0 || i % 5 == 0) {
                arrayOfSelected.add(i)
            }
        }
        Log.i("TAG", "multiplesOf: $arrayOfSelected")
    }

Solution

The only bug is in your boolean expression:

Given i=0

i != 0 && i % 3 == 0 // this is false
||
i % 5 == 0 // this is true

This is basic Bool’s arithmetic: false or true => true and hence will execute your if’s block

Adding parenthesis might help you get the desired outcome:

if ( i != 0 && (i % 3 == 0 || i%5 ==0) ) {...}

Answered By – Some random IT boy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published