aspose file tools*
The moose likes Beginning Java and the fly likes Exception Handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception Handling" Watch "Exception Handling" New topic
Author

Exception Handling

Marie Jeanne Thibault
Greenhorn

Joined: Nov 15, 2003
Posts: 15
Hi Everyone,
I'm wondering if you can help me with this...I want a message to be displayed if args[1] and args[2] are anything but integers. I know my "if" statements are not right but that's what I want it to do. How do I make this work? Here's my code...
//ExceptDemo1a.java
public class ExceptDemo1a
{
//Main Method with three arguments
//args[0]: operator
//args[1]: operand1
//args[2]: operand2
public static void main(String[] args)
{
//Declare and initialize variables
int result = 0;
int operand1 = 0;
int operand2 = 0;
if(operand1 != int)
{
operand1 = new Integer(args[1]).intValue();
try
{
switch (args[0].charAt(0))
{
case '+': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
break;
case '-': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
break;

case '*': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
break;
case '/': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
}
}
catch(Exception ex1)
{
System.out.println("Input must be an integer");
}
}

else if(operand2 != int)
{
operand2 = new Integer(args[2]).intValue();
try
{
switch (args[0].charAt(0))
{
case '+': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
break;
case '-': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
break;

case '*': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
break;
case '/': result = Integer.parseInt(args[1]) +
Integer.parseInt(args[2]);
}
}
catch(Exception ex2)
{
System.out.println("Input must be an integer");
}
}

//Display the result
System.out.println(args[1]+ ' ' +args[0]+ ' ' +args[2]+ "=" +result);
}
}

Any help would sure be appreciated!!!
Thanks,
Marie
karl koch
Ranch Hand

Joined: May 25, 2001
Posts: 388
hi

you can use a try/catch block because the parseInt method throws a NumberFormatException:

- you can use 'operand1' and 'operand2' in your switch statement (should make the code a bit more readable) instead of the Integer.parseInt() statements.
- you should check if the args array has the good length
- you can also check if the operator is valid

cheers and a happy new year
K
Marie Jeanne Thibault
Greenhorn

Joined: Nov 15, 2003
Posts: 15
Thanks Karl, worked like a charm.
Marie
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception Handling