Day 16: Exceptions - String to Integer

Sort by

recency

|

990 Discussions

|

  • + 0 comments

    Hi Can someone explain why this makes the test to fail (while the output is ok..) ? Thanks in advance

    'use strict';
    
    process.stdin.resume();
    process.stdin.setEncoding('utf-8');
    
    let inputString = '';
    let currentLine = 0;
    
    process.stdin.on('data', function(inputStdin) {
        inputString += inputStdin;
    });
    
    process.stdin.on('end', function() {
        inputString = inputString.split('\n');
    
        main();
    });
    
    function readLine() {
        return inputString[currentLine++];
    }
    
    
    
    function main() {
        const S = readLine();
        
         try {
            const parsed = parseInt(S, 10)
            if (!/^\d+$/.test(S) || isNaN(parsed)) {
                throw new Error("Bad String");
            }
            console.log(parsed);
        } catch (err) {
            console.log("Bad String");
        }
    }
    
  • + 0 comments
    C#
    
            string s = Console.ReadLine() ?? "";
            int ints = 0;
            try 
            {
                ints = int.Parse(s);
                Console.Write($"{ints}");
            }
            catch
            {
                Console.Write("Bad String");
            }
    
  • + 0 comments

    i dont know why my answer is wrong the output ic correct-#!/bin/python3

    import sys

    if name == 'main': S = input().strip() # Read input and strip leading/trailing whitespaces

    try:
        # Try to convert the string to an integer
        print(int(S))
    except ValueError:
        # If it fails, print "Bad String"
        print("Bad String")
    
  • + 0 comments

    Here's the ugly Typescript that doesn't use conditionals, lol.

    function fail() {
        throw new Error("Not an int")
    }
    
    function main() {
        const S: string = readLine();
        try {
            const num = Number(S)
            const test = !Number.isInteger(num) && fail()
            console.log(num)
        } catch (e) {
            console.log("Bad String")
        }
    }
    
  • + 1 comment

    I don't think you can actually complete this task using Typescript as the resulting number is just NaN and throwing your own error will fail becasue you have an if statement.