String to integer conversion with error handling

Report a typo

Imagine you are writing a program that converts a string to an integer number in Kotlin. Your task is to handle cases where input string cannot be converted to a number using appropriate exception handling in Kotlin. Create a simple program on Kotlin to perform this conversion. Calculate the length of the resulting number, but if it fails to convert, return '-1'. Your program will read a string as an input and output an integer representing the length of digits in the converted number from that string.

Sample Input 1:

99999999

Sample Output 1:

8

Sample Input 2:

abcd

Sample Output 2:

-1
Write a program in Kotlin
// Necessary import statements
import java.lang.Exception
import java.lang.NumberFormatException

// Function to convert String to Integer and calculate its length
fun stringToIntLength(input: String): Int {
// Placeholder where the exception handling logic shall go
// This is where your responsibility as a programmer begins

// Remember all exceptions derive from the Exception superclass, but we are dealing with a NumberFormatException

// After handling the exceptions, convert the string to an Integer and get its length
// If it fails to convert, return -1
}

// Entry point of the program
fun main(args: Array<String>) {
val strInput = readLine().toString()

// Call the previously declared function with `strInput` as an argument
println(stringToIntLength(strInput))
}
___

Create a free account to access the full topic