Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
Marie Jeanne Thibault
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 388
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Karl, worked like a charm.
Marie
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic