Day 16: Exceptions - String to Integer

  • + 0 comments

    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:

    function throwBadString(): never {
        throw new Error("Bad String");
    }   
    
    function main() {
        const S: string = readLine();
        
        try {
            const num = parseInt(S);
            isNaN(num) && throwBadString();
            console.log(num);
        } catch (error) {
            console.log("Bad String");
        }
    }
    

    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:

    public class Solution {
        public static void main(String[] args) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    
            String S = bufferedReader.readLine();
            
            try {
                int result = Integer.parseInt(S);
                System.out.println(result);
            } catch (NumberFormatException e) {
                System.out.println("Bad String");
            }
    
            bufferedReader.close();
        }
    }