Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

766
Visualizações
How can I change number to negative number in kotlin

The absolutes variable represents a number. The sign attempts to convert "-" into a number "++" when "negative number" is "positive number". We're going to solve the task of adding all the variables that we changed.

a[i] = absolutes[i].unaryMinus()

In this sentence, Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

An error appears.

Can I know which part is wrong?

    val absolutes = intArrayOf(4,7,12)
    val sign = arrayOf(true,false,true)

    val a = intArrayOf(0)

    for (i in absolutes.indices){

        if (!sign[i]) {
            a[i] = absolutes[i].unaryMinus()
        }
    }

    val result = a.sum()

    Log.d(logTag, "onCreate is called result = $result")
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

intArrayOf from the Kotlin standard library "Returns an array containing the specified Int numbers".

Thus, your value of a is an IntArray of size 1. You cannot assign values to indices above the lastIndex, which in this case is 0.

I assume you aimed to create an IntArray of the same size as your input, filled with zeroes by default.

val a = IntArray(absolutes.size)
over 4 years ago · Santiago Trujillo Relatório

0

You have created an array a with 1 element so when referencing a[1] you are hitting the ArrayIndexOutOfBoundsException. Either declare the array as val a = intArrayOf(0, 0, 0) or reduce the initial array.

val absolutes = intArrayOf(4, 7, 12)
val sign = arrayOf(true, false, true)

absolutes.foldIndexed(0) { index, acc, element ->
    return@foldIndexed if (sign[index]) {
        acc + element
    } else {
        acc - element
    }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda