Day 16: Exceptions - String to Integer

Sort by

recency

|

1000 Discussions

|

  • + 0 comments

    for code java public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String S = sc.nextLine(); try{ int num = Integer.parseInt(S);
    System.out.println(num); }catch(Exception e){ System.out.println("Bad String"); }

    }
    

    }

  • + 0 comments

    public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String S = sc.nextLine(); try{ int num = Integer.parseInt(S);
    System.out.println(num); }catch(Exception e){ System.out.println("Bad String"); }

                for java code 
    
    
    
    }
    

    }

  • + 0 comments

    for js

    function main() { const S = readLine();console.log(parseInt(S)?S:'Bad String') }

  • + 0 comments

    If anyone is trying to solve this problem in Python3. Then use this code not the pre-defined code:

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    S = input().strip()
    try:
        print(int(S))
    except ValueError:
        print("Bad String")
    
  • + 1 comment

    For JS this worked:

    function main() {
      const S = readLine();
      try {
        const num = JSON.parse(S);
        console.log(num);
      } catch (e) {
        console.log("Bad String");
      }
    }
    

    But for Python I get: Error reading result file.You should use exception handling concepts.

    I tried this:

        S = input()
        
        try:
            num=int(S)
            print(num)
        except ValueError: 
            print("Bad String")
    

    and this:

        S = input()
        
        try:
            num=int(S)
            print(num)
        except: 
            raise Exception("Bad String")
    

    None of these worked.

    • + 0 comments

      I think it specifically wants you to notice, in the exception, that it's a ValueError. So try specifying the exception