Value insertion problem in an array/list

Asked

Viewed 33 times

1

I am trying to insert a number into a list/array but on condition if are you saying: No get method providing array access

import java.util.Scanner

fun main(){

    val input = Scanner(System.`in`)
    var num:Int

    for(i in  0 until 5){
        println("Insira um numero entre 0 e 10: ")
        num  = input.nextInt()

        if(num[i]<0 or num[i]>10{
            println("INVALIDO")
        }else{
            i++
        }

    }

    for(i in num) print(i)
}
  • 1

    num is an integer and not a list

1 answer

2


Overall, your logic doesn’t make much sense.

You need to create a list to store the numbers and instead are trying to access indexes in a variable of type Int.

You need, basically, this:

import java.util.Scanner

fun main() {

    val input = Scanner(System.`in`)

    // Criar uma lista para armazenar todos os números
    var listaNumeros = mutableListOf<Int>()

    for(i in 0 until 5){
        println("Insira um numero entre 0 e 10: ")
        
        // Essa variável vai receber cada input do usuário
        val num = input.nextInt()

        // A validação precisa ser no valor que o usuário digitou
        if(num < 0 || num > 10) {
            println("INVALIDO")
            continue // Continua o loop caso a validação falhe
        }

        // Adiciona o número na lista
        listaNumeros.add(num)
    }

    for(i in listaNumeros) print(i)
}
  • thank you very much, helped me a lot, because I was very confused of how I did

  • Read this material to understand how the collections work in Kotlin.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.