So this is a class that is meant to take in as input in the CMD prompt a string and integer, i.e. "Hello" 4, and then repeat the string 4 times. Thats not a problem, and works, however I want to return an error message (i.e. "Invalid argument") if the second argument, (arg[1]) is either not a positive integer (args[1]>0) or if its not even of an integer type normally. I can test if its not a positive integer, but I could do with a hand on how to compare whether the contents of a string array is or isn't parsable to an integer?
public class Repeat {
public static void main(String[] args) {
System.out.println(parseAndRep(args));
}
public static String parseAndRep(String[] args){
if (args.length<2){
return"Error: insufficient arguments";
}
if (Integer.parseInt(args[1]<1) || **//TODO Work out if correct type**) {
return "Error: second argument not a valid positive integer";
}
int n = Integer.parseInt(args[1]);
String repeatstring = args[0];
while (n!=1){
repeatstring = repeatstring +" "+ args[0];
n= n-1;
}
return repeatstring;
}
The args
parameter of the main()
method is always of type String[]
. What you want to do is not to check the type (that has another meaning entirely), but you want to see if the String
instance you have is parseable into an integer. To do that you can always check to see that the string matches a regular expression that only accepts digits:
if(!args[1].matches("\\d+"); {
return "Error: second argument is not a valid positive integer";
}