Java command arguments - How to print only certain strings

74 Views Asked by At

Learning command arguments in Java, trying to print only names in a string of names and ages.

So instead of Bill 32 Mary 42 Bob 29 Lisa 20

I should get Bill Mary Bob Lisa

class CmdArgsNameAgePairs
{
    public static void main(String[] args)
    {

         java CmdArgs Bill 32 Mary 42 Bob 29 Lisa 20
                 //Bill is 32
                 //Mary is 42

        int i=0;//initial index
        while (i <= args.length-1) 
        {           
            System.out.println(args[i]);
            i++;        
        }
    }
}
                // System.out.println(args[0]);
        // System.out.println(args[2]);
        // System.out.println(args[4]);
            // System.out.println(args[6]);
3

There are 3 best solutions below

0
On

Try this.

for (int i = 0; i < args.length; i += 2)
    System.out.println(args[i]);
0
On

It could be something like this:

int i = 0;
while (i < args.length) {
    if (i % 2 == 0) {
        System.out.println(args[i]);
    }
    i++;        
}
0
On

You may choose to use regular expressions to check if the value consists of alphabets only as well:

int i=0;//initial index
while (i <= args.length-1) {
    if(args[i].matches ("[a-zA-Z]+")){
        System.out.println(args[i]);
    }
    i++;
}