How To Input Numbers From Command-Line Arguments Then Store Only Prime Numbers To An Integer Array In Java.

Input numbers from command-line arguments then store only prine numbers to an array in java

1. Short introducation to use of command line argument in java.

2. Source Code.

Short introducation to use of command line argument in java :

The java command-line argument is an argument i.e. passed at the time of running the java program. The arguments passed from the console can be received in the java program and it can be used as an input. So, it provides a convenient way to check the behavior of the program for the different values.

Source Code :

package gsh.java.programs;
public class commandLineDemo1   {
    public static void main(String[] args) throws ArrayIndexOutOfBoundsException,ArithmeticException {
        for (int i=0;i<args.length;i++) {
             int isPrime = 1;
                for (int j=2;j<Integer.parseInt(args[i]);j++){
                    if(Integer.parseInt(args[i])%j==0){  //Check all the particular integer numbers from the  command line argument
                        isPrime = 0;
                        break;
                    }
                }
            if(isPrime==1){
                int[] array = new int[i+1];//Defining array
               array[i] = Integer.parseInt(args[i]); //Store all the prime numbers in an array
                System.out.print(array[i]+" "); // printing array
            }
        }
    }
}

Output:

Command Line Argument : 10 11 15 16 31 51
Output : 11 31

Post a Comment

0 Comments