Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need to test argument for contents 1

Status
Not open for further replies.

blues77

Programmer
Jun 11, 2002
230
0
0
CA
Hello,

I need a way to check an argument that is passed on the command line to my application to make sure that it is a positive number. For example if I ran "application abc 3"
my code should check each of the arguments in this case "abc" and "3" and it should alert the user that argument "abc" is not a number (in other words I can't use Integer.parseInt) to extract a number. Any suggestions on how I could do this would be appreciated!

Thanks
Mike
 
The Integer.parseInt method throws a NumberFormatException "if the string does not contain a parsable integer".(
You should be able to catch the exception like this:

for (int i = 0; i < args.length; i++) {
try {
Integer.parseInt (args);
}
catch (NumberFormatException e) {
System.out.println ("Argument "+args+ " is not an integer.")
}
}
 
public class inp
{
public static void main(String args[])
{
//System.out.println(args.length);
int i=0;
boolean isInvalid[] = new boolean[10];
if (args.length>0)
{
for (i=0; i<args.length; i++)
{
//System.out.println("***"+args[0].length());
for (int whichChar=0; whichChar<args[0].length(); whichChar++)
{
//System.out.println(args.length()+"position"+whichChar);
if ( args.charAt(whichChar)<'0' || args.charAt(whichChar)>'9')
{
if (args.charAt(whichChar)!='.')
{
isInvalid = true;
}
}
}
}
for (int m=0; m<args.length; m++)
if (isInvalid[m])
System.out.println(m+" argument "+args[m]+" is not a number");
}
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top