Day 16: Exceptions – String to Integer(30 Days of Code)

Task

Read a string, S, and print its integer value; if  cannot be converted to an integer, print Bad String.
Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a 0 score.

Input Format

A single string, S.

Output Format

Print the parsed integer value of S, or Bad String if S cannot be converted to an integer.

Sample Input

3/za

Sample Output

3/Bad String

Explanation

Sample Case  contains an integer, so it should not raise an exception when we attempt to convert it to an integer. Thus, we print the .
Sample Case  does not contain any integers, so an attempt to convert it to an integer will raise an exception. Thus, our exception handler prints Bad String.

Solution:

1)Javascript

function main() {
     const S = Number(readLine());
     try{
        Number.isNaN(S)?error:console.log(S);
     }catch(err){
         console.log("Bad String");
     }
 }

2)Java

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