Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this Kotlin code not working? (If str[index] in list then print)

import kotlin.reflect

fun main(args: Array<String>) {
    
    val cons = listOf("B","C","D", "F", "G", "H", "J", "K", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z",)
        
    var str = "JBIKCA"
    
       for (item in str.indices) {
        val j = (str[item])
         if (j in cons){
          println(j)
         }             
    }

Apologies for the basic question but this is my first time with the language.

Correct Output should be:

J
B
K
C

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that j is a Char where cons contains String elements.

Simply convert the characters to string before checking. You can also more simply iterate str using for..in

for (j in str) {
    if (j.toString() in cons) {
        println(j)
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading