*homework
Using the command line command
java class -add 7 8
will add all integers after "-add". But for this program, I am also suppose to print "Argument type mismatch" if anything after "-add" is not an integer.
I have this method to search a String for integers. If it finds something other than an integer, it returns false.
public static boolean isInteger(String s) {
try {
int num = Integer.parseInt(s);
return true;
} catch (Exception e) {}
return false;
}
Now in this method I try to use the isInteger method to look at a String in the first for loop.
private static void add(String[] args) {
for (int j = 1; j < args.length; j++) {
if (isInteger(args[j]) == false)
System.out.println("Argument type mismatch");
}
if (args.length == 1)
System.out.println("Argument count mismatch");
else {
int result = 0;
for (int i = 1; i < args.length; i++) {
result += Integer.parseInt(args[i]);
}
System.out.println(result);
}
}
Running the first for loop by itself produces "Argument type mismatch" perfectly fine. But when I run the whole method and type the command
java class -add cat
it produces "Argument type mismatch" followed by a java.lang.NumberFormatException: For input string: "cat" error at the line result += Integer.parseInt(args[i]);
How can I fix this error?
return;afterSystem.out.println("Argument type mismatch");should solve it.