Reputation: 35
How do I print something when a command line argument is not an integer and a NumberFormatException
occurs?
My program takes 3 command line arguments and prints certain text depending on what they are.
Here's the code:
public class CommandLine {
public static void main(String[] args) {
if(args.length !=3){
System.out.println("Error. Must give 3 values");
}
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int z = Integer.parseInt(args[2]);
if((x%2)==0 && (y%2)==0 &&(z%2)==0)
System.out.println("Even");
else
System.out.println("odd");
}
}
Upvotes: 0
Views: 759
Reputation: 517
Try this
public class CommandLine {
public static void main(String[] args) {
if(args.length !=3){
System.out.println("Error. Must give 3 values");
}
try{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int z = Integer.parseInt(args[2]);
if((x%2)==0 && (y%2)==0 &&(z%2)==0)
System.out.println("Even");
else
System.out.println("odd");
}catch(Exception e){
System.out.println("Exception Caught !");
}
}
}
Upvotes: 1
Reputation: 4135
if(args.length !=3){
System.out.println("Error. Must give 3 values");
}
else//if the above condition if true so skip these statements
{
try
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int z = Integer.parseInt(args[2]);
if((x%2)==0 && (y%2)==0 &&(z%2)==0)
System.out.println("Even");
else
System.out.println("odd");
}
catch(NumberFormatException ne)
{
System.out.println("Plz! pass only integer values");//catching number format exception
}
}
Upvotes: 1
Reputation: 5040
You can catch that exception and print :
int x=y=z=Integer.MIN_VALUE;
try{
x = Integer.parseInt(args[0]);
y = Integer.parseInt(args[1]);
z = Integer.parseInt(args[2]);
}catch (NumberFormatException e) {
System.out.println("x:" +x + " y:" +y +" z:" +z);
e.printStackTrace();
}
The first value which is still Integer.MIN_VALUE
caused your exception(unless your number is Integer.MIN_VALUE
)
Upvotes: 3