We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Day 16: Exceptions - String to Integer
Day 16: Exceptions - String to Integer
Sort by
recency
|
994 Discussions
|
Please Login in order to post a comment
🐍 If your try: except code can't get validation - try to delete 'if name == 'main':'
Probably this if statement triggers an error message reading it as part of "if (...) else") statement.
Graditudes:
https://www.hackerrank.com/karinaxfarias https://www.hackerrank.com/przemyslaw_siek1
I made a code in python using try and except, however this error is appearing in the submition "Error reading result file.You should use exception handling concepts." if name == 'main': S = input() try: integer=int(S) print(str(integer)) except ValueError: print("Bad String") pass except Exception: print("Bad String")
Solution in JavaScript/TypeScript
In JavaScript/TypeScript, the situation is a bit different. The parseInt function does not throw an exception when the conversion fails. Instead, it returns NaN (Not-a-Number), which means we need additional validation to handle this case. Due to the challenge's restrictions, which do not allow the use of conditionals, it was not possible to submit a solution that met all the requirements. Here is an attempt at a solution in TypeScript using parseInt for conversion, but it requires additional validation for NaN:
Solution in Java
In Java, the solution was straightforward thanks to Integer.parseInt, which throws a NumberFormatException if the string cannot be converted to an integer. This allows us to handle the conversion error clearly and simply using a try-catch block. Here's the code:
Hi Can someone explain why this makes the test to fail (while the output is ok..) ? Thanks in advance