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.
Taming exceptions
String to integer conversion with error handling
Report a typo
Sample Input 1:
99999999Sample Output 1:
8Sample Input 2:
abcdSample Output 2:
-1Write 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))
}
___
By continuing, you agree to the JetBrains Academy Terms of Service as well as Hyperskill Terms of Service and Privacy Policy.
Create a free account to access the full topic
By continuing, you agree to the JetBrains Academy Terms of Service as well as Hyperskill Terms of Service and Privacy Policy.