In: Computer Science
Write a complete main method that does the following: Takes any number, but at least two, command line arguments which are words (represented as strings) and will print to the console the number of words of that end with a digit. (Hint: loop through the args array)
If there are not at least two command line arguments, throw an IllegalArgumentException with an appropriate message.
Please find the code below:
public class CLA {
public static void main(String[] args) throws IllegalArgumentException{
if(args.length < 2) //if less than 2 words entered
{
throw new IllegalArgumentException("Enter more than 2 args"); //throw exception
}
else
{
int count = 0; //count of words
for(String s : args) //iterate through args
{
if(Character.isDigit(s.charAt(s.length() - 1))) //if character at last index is a digit
{
count++; //increment count
}
}
System.out.println("Number of words that end with a number are : "+count); //display count
}
}
}
Supplied Input:
Corresponding Output:
Number of words that end with a number are : 3
Thanks, Please upvote if you appreciate the effort. :)