1

Is there a way to code something like this in kotlin for a variable number of ints? For example the input should be "1 3 5" or "3 2 2 7" (String with space-separated Ints). And I am not allowed to use java librarys.

val (x, y) = readLine()!!.split(' ').map(String::toInt) println(x+y) 

Thanks in advance.

3
  • 2
    What does your input look like? Commented May 29, 2020 at 0:19
  • I edited the question, I do not need strings, I need ints :D The input should be something like "2 3 4" or "1 8 5 2". Just a variable number of random ints. Commented May 29, 2020 at 0:50
  • 3
    It’s really unclear what your asking. Is the input a list of Ints or a String with space-separated Ints? And what is the “this” in “something like this”? Commented May 29, 2020 at 0:55

2 Answers 2

2

If you want to just print each string, then you can use forEach

readLine()!!.split(' ').forEach{ println(it) } 

If you want to print as int, then you can use forEach with toInt()

readLine()!!.split(' ').forEach{ println(it.toInt()) } 

Or if you want sum you can use sumBy directly

readLine()!!.split(' ').sumBy{ it.toInt() } 
Sign up to request clarification or add additional context in comments.

Comments

0

Found a solution for my problem:

var list: List<Int> = readLine()!!.split(' ').map(String::toInt) for(m in list){ println(m) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.