Home > Net >  How to take two different data type user input in one line in KOTLIN?
How to take two different data type user input in one line in KOTLIN?

Time:11-15

var (a,b)= readLine()!!.split(" ").map { it.toInt() }

its about to take one kind of data type in one line. But how can i take two different data type same as above? like- "integer" space "float" I have to take user input- integer a and float b in one line with a space. // 1 2.0

fun main(){
    //var (a,b)= readLine()!!.split(" ").map { it.toInt() }
    var a = readLine()!!.toInt()
    var b= readLine()!!.toFloat()
    if (a>b){
        var roundNumber= "%.2f".format(b)
        println(roundNumber)
    }
    else if (a%5==0 && b>=a 0.5){
        var c= b-(a 0.5)
        var roundNumber= "%.2f".format(c)
        println(roundNumber)
    }
    else{
        var roundNum= "%.2f".format(b)
        println(roundNum)
    }
}

Input: 30 120.00 Output: 89.50 (It's Working) .... But the fact is i have to put input two in one line with a space. Input: 30 120.00

CodePudding user response:

You are trying to map both string representations of an integer and a floating point number using toInt() which will return null for the floating point input which is not what you want.

One solution would be to split the line into a list of strings and then convert them separately

val components = readLine()!!.split(" ")
val a = components[0].toInt()
val b = components[1].toFloat()

Another option is to use a Java scanner

First import the scanner at the top of your file.

import java.util.Scanner

Then create a scanner object and use it to extract the values from the input line.

  val scanner = Scanner(readLine())
  val a = scanner.nextInt()
  val b = scanner.nextFloat()
  • Related