In: Computer Science
In Java:
Write a complete main method that does the following: 1. 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) 2. If there are not at least two command line arguments, throw an IllegalArgumentException with an appropriate message.
Here is the Java code to given question.
Sample outputs are added at the end.
Code:
public class CommandLineTest {
public static void main(String[] args){
try{
if(args.length<2){ /*if number of words in command line arguments is less than 2*/
throw new IllegalArgumentException(); /*throws new IllegelArgumentException*/
}
else{
int numberOfWords=0; /*uswed to store number of words that end with a digit*/
String currentWord; /*used to store current word of command line argument*/
for(int i=0;i<args.length;i++){ /*runs through all command line arguments*/
currentWord=args[i]; /*stores current word in a variable*/
int lastIndex=currentWord.length()-1; /*computes the last index of currentWord*/
if(Character.isDigit(currentWord.charAt(lastIndex))){ /*checks if the current word ends with a digit*/
numberOfWords+=1; /*increments the number of words by 1*/
}
}
System.out.println("Number of words that end with a digit: "+numberOfWords); /*prints the number of words that end with a digit*/
}
}catch (IllegalArgumentException e){
System.out.println(e+": There should be atleast 2 command line arguments."); /*prints exception with appropriate message*/
}
}
}
Sample output-1:
Command line arguments:
Output:
Sample output-2:
Command line arguments:
Output: