#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    1
    Rep Power
    0

    Exception Handling for a Calculator


    Hello,

    So I need to write a program that acts like a calculator. I need to code exceptions for three different scenarios.

    1. Divide by zero
    2. imputing a wrong operator (+ - / *)
    3. imputing a non integer

    I got divide by zero to work but can't seem to get the other 2 work...

    Here is the code:

    import java.util.*;

    public class calculator
    {

    static boolean _state =true;

    public static void main (String[] args)
    {
    System.out.println("Usage: operad1 operator operand2");
    System.out.println(" (operands are intergers)");
    System.out.println(" (operators: + - * /)");
    @SuppressWarnings("resource")
    Scanner keyboard = new Scanner(System.in);


    do {

    int result = 0;
    int operand1 = 0;
    int operand2 = 0;
    String operator = "";
    char op = ' ';

    operand1 =keyboard.nextInt();
    operator = keyboard.next();
    op = operator.charAt(0);
    operand2 = keyboard.nextInt();
    try{

    switch (op)
    {

    case '+':result = operand1 + operand2;
    System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result );
    break;

    case '-': result = operand1 - operand2;
    System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result );
    break;

    case '*': result = operand1 * operand2;
    System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result );
    break;

    case '/': result = operand1/operand2;
    System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result );
    break;
    default:
    System.out.println("Enter an appropriate operator");
    break;
    }

    }

    catch(ArithmeticException e){
    System.out.println("Cannot divide by zero ");
    }

    try{
    keyboard.nextInt();
    }
    catch(InputMismatchException ex){


    System.out.println("The input is not an integer.");
    }

    }
    while (_state == true );

    }
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    103
    Rep Power
    3
    Your problem is that your initial input isn't surrounded in a try catch block, so if an exception is detected, then Java throws the exception and closes the program.

    The InputMismatchException is thrown when Scanner is expecting a certain data type, but gets another as its input.

    e.g. if you say Scanner.nextInt() but you are given a String, then Java will throw that exception. You need to make sure that you are surrounding every statement like this with a try catch if you want to handle those exceptions.

    Also, please surround your code with [code] tags

IMN logo majestic logo threadwatch logo seochat tools logo