Write a program that prompts the user to enter a non-negative integer. If the user enters a negative integer, the program should catch the exception and print an error message. Otherwise, the program should print the square of the input integer.
Try-catch statement
Handling negative integers gracefully
Report a typo
Sample Input 1:
5Sample Output 1:
25Sample Input 2:
-3Sample Output 2:
Invalid input! Please enter a non-negative integer.Write a program in Kotlin
import kotlin.NumberFormatException
fun main() {
// Read user input as a string
val input = readLine()
try {
// TODO: Convert the input string to an integer
// TODO: Check if the integer is non-negative
// TODO: If the integer is non-negative, print its square
// TODO: If the integer is negative, throw an exception with an error message
} catch (e: NumberFormatException) {
// TODO: Handle the exception if the input is not a valid integer
}
}
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.