0

I'm trying to learn Kotlin from Python and I need some help with how to create an array of different types using scanner class but keep getting an error java.lang.ArrayIndexOutOfBoundsException. Thanks in advance.

fun main(){

    val scanner = Scanner(System.`in`)
    println("Enter your name: ")
    println("Enter your height in inches: ")
    println("Enter your weight: ")
    val (name, height, weight) = arrayOf(scanner)
    println("your name is $name, your height is: $height your weight is $weight")

}
2
  • Are you struggling with having different types? Or creating an array with the users inputs? Because arrayOf(scanner) is just an array with your single scanner instance. Commented Mar 21, 2021 at 16:56
  • The issue i'm having is creating the array with multiple values. Should I be using a for loop for each value instead of val (name, height, weight)? I can convert the types later in my program. All i'm trying to do for now is create the array, or does it need to be a list? Commented Mar 21, 2021 at 18:04

1 Answer 1

1

Well in Kotlin, as well in Java, it is a bit different to get the input from the scanner, so try this:

val reader = Scanner(System.`in`)
    println("Enter your name: ")
    println("Enter your height in inches: ")
    println("Enter your weight: ")

    val (name, height, weight) = arrayOf(reader.next(), reader.nextInt(), reader.nextInt())
    println("your name is $name, your height is: $height your weight is $weight")

So if you wanted to wait for the inputs, you need to declare variables after `print()` or `println()` and init it to `scanner.next()` functions, then at the end you create your array in a single line using the variables.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.