Algorithm


Problem Name: 30 days of code - Day 16: Exceptions - String to Integer

Problem Link: https://www.hackerrank.com/challenges/30-exceptions-string-to-integer/problem?isFullScreen=true

Objective
Today, we're getting started with Exceptions by learning how to parse an integer from a string and print a custom error message. Check out the Tutorial tab for learning materials and an instructional video!

Task
Read a string,  S, and print its integer value; if S 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.

Constraints

  • 1 <= |S| <= 6, where |S| is the length of string S.
  • S is composed of either lowercase letters (a - z) or decimal digits (0 - 9).

Output Format

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

Sample Input 0

3

Sample Output 0

3

Sample Input 1

za

Sample Output 1

Bad String

 

 

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming


#include <iostream>

using namespace std;

int main() {
    try {
        string str;
        cin >> str;

        int num = stoi(str);
        cout << num;
    }
    catch (...) {
        cout << "Bad String";
    }
    return 0;
}

Copy The Code & Try With Live Editor

#2 Code Example with C# Programming

Code - C# Programming


using System;

class Solution
{
    static void Main(String[] args)
    {
        var str = Console.ReadLine();

        try
        {
            int num = int.Parse(str);
            Console.WriteLine(num);
        }
        catch (Exception)
        {
            Console.WriteLine("Bad String");
        }
    }
}
Copy The Code & Try With Live Editor

#3 Code Example with Java Programming

Code - Java Programming


import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String string = in.next();
        in.close();
        try {
            Integer integer = Integer.parseInt(string);
            System.out.println(integer);
        } catch (NumberFormatException numberFormatException) {
            System.out.println("Bad String");
        }
    }
}
Copy The Code & Try With Live Editor

#4 Code Example with Javascript Programming

Code - Javascript Programming


'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 {
        isNaN(Number(S)) ? error : console.log(S)
    }
    catch (err) {
        console.log('Bad String')
    }
}
Copy The Code & Try With Live Editor

#5 Code Example with Python Programming

Code - Python Programming


try:
    print(int(input().strip()))
except ValueError:
    print("Bad String")
Copy The Code & Try With Live Editor

#6 Code Example with PHP Programming

Code - PHP Programming



Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Day 15: Linked List solution in Hackerrank - Hacerrank solution C, C++, C#, java, Js, Python in 30 days of code
Next
[Solved] Day 17: More Exceptions solution in Hackerrank - Hacerrank solution C, C++, C#, java, Js, Python in 30 days of code