[Solved] Command Line Argument Print String or Integer with Java, C++

Command Line Argument Print String or Integer: Write a  program to accept an integer or string as command line argument and print whether the given input is string or integer

Sample Input (Command Line Argument) 1:
abc

Sample Output 1:
The given input is a string

Sample Input (Command Line Argument) 2:
5

Sample Output 2:
The given input is an integer

Solution

import java.util.*;
class Main
{
    static boolean isNumber(String s)
    {
        for (int i = 0; i < s.length(); i++)
            if (Character.isDigit(s.charAt(i)) == false)
                return false;
 
        return true;
    }
    
    public static void main(String jr[])
    {  
        if (isNumber(jr[0]))
        {
            System.out.println("The given input is an integer");
        }
        else
        {
        System.out.println("The given input is a string");
        }
        
    }
}
#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{
    if (argc == 2)
    {
        if (atoi(argv[1]) == 0)
        {
            //sauravhathi
            cout << "The given input is a string" << endl;
        }
        else
        {
            //sauravhathi
            cout << "The given input is an integer" << endl;
        }
    }
    else
    {
        cout << "Invalid input" << endl;
    }
    return 0;
}
Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *