Search code examples
javafor-loopforeachargumentsprogram-entry-point

Looping through all main() arguments


  • The application will request a series of input words/string using the main arguments.
  • It will determine if per input string entered ends in a consonant, a vowel, an odd number, an even number, or a special symbol.
  • It should also be able to count the number of characters per word input.

So far, this is what I have:

public static void main(String[] args) {
    if(args.length > 0) {
        String regExVowels = ".*[AEIOUaeiou]$";
        // regEx Strings

        char[] caMainArg = null;
        String strMainArg = null;

        for(String arg: args) {
            // Convert each String arg to char array
            caMainArg = arg.toCharArray();

            // Convert each char array to String
            strMainArg = new String(caMainArg);
        }

        System.out.print(strMainArg + " - " + strMainArg.length());

        // if-else conditions

    } else {
        System.out.println("No arguments passed!");
    }
}

It works, but it only takes the last argument. For example:

Eclipse > Run Configurations... > Arguments

kate middleton sep30 jan25 `

It will only output:

` - 1 - special character

My desired output is:

kate - 4 - vowel
middleton - 9 - consonant
sep30 - even number
jan25 - odd number
` - 1 - special character

I am unsure as to how to loop through the arguments and print the appropriate results.


Solution

  • You close your for loop too early.

    You do:

       for(String arg: args) {
            // Convert each String arg to char array
            caMainArg = arg.toCharArray();
    
            // Convert each char array to String
            strMainArg = new String(caMainArg);
        }
        System.out.print(strMainArg + " - " + strMainArg.length());
    
        if(regExVowels.matches(strMainArg)) {
            System.out.print(" - vowel");
    
        } else if(regExUpperConsonants.matches(strMainArg) ||
    
        .....
    

    You need to do :

       for(String arg: args) {
            // Convert each String arg to char array
            caMainArg = arg.toCharArray();
    
            // Convert each char array to String
            strMainArg = new String(caMainArg);
            System.out.print(strMainArg + " - " + strMainArg.length());
    
            if(regExVowels.matches(strMainArg)) {
                System.out.print(" - vowel");
    
            } else if(regExUpperConsonants.matches(strMainArg) ||
    
            ....
    
        }