I have a Calculator program below that I wrote. I need it to write an exception handler that deals with non-numeric operands. I know the exception error i need is Number Format Exception but I am having a hard time with my try and catch block so I took it off temporarily until I can get it to work. THis is my code:

public class Calculator
 {
  /** Main method */
  public static void main(String[] args)
 {
    // Check command-line arguments
    if (args.length != 3) 
{
      System.out.println( "Usage: java Calculator operand1 operator operand2");
      System.exit(0);
    }

    // The result of the operation
    int result = 0;

    // Determine the operator
    switch (args[1].charAt(0))
 {
      case '+': result = Integer.parseInt(args[0]) +
                         Integer.parseInt(args[2]);
                break;
      case '-': result = Integer.parseInt(args[0]) -
                         Integer.parseInt(args[2]);
                break;
      case '*': result = Integer.parseInt(args[0]) *
                         Integer.parseInt(args[2]);
                break;
      case '/': result = Integer.parseInt(args[0]) /
                         Integer.parseInt(args[2]);
    }

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

Recommended Answers

All 4 Replies

It would be more useful to see the code with the try-catch block(s) included to know what you have tried.

I would recommend a try-catch on the parsing of each arg and in the catch, print the usage and the argument that caused the exception.

ok guys this is what I get when I use the Number Format Exception but now Im getting an error with my parenthesis. I get ')' expected on the same line twice. Please help me!!

import javax.swing.*;

public class Calculator
 {
  /** Main method */
  public static void main(String[] args) {
    // Check command-line arguments
    if (args.length != 3) 
        {
      System.out.println
        ("Usage: java Calculator operand1 operator operand2");
      System.exit(0);
    }
 double numBuffer;

    // The result of the operation
    int result = 0;


    // Determine the operator
    switch (args[1].charAt(0))
         {
      case '+': result = Integer.parseInt(args[0]) +
                         Integer.parseInt(args[2]);
                break;
      case '-': result = Integer.parseInt(args[0]) -
                         Integer.parseInt(args[2]);
                break;
      case '*': result = Integer.parseInt(args[0]) *
                         Integer.parseInt(args[2]);
                break;
      case '/': result = Integer.parseInt(args[0]) /
                         Integer.parseInt(args[2]);
    }
try
{
result=Double.toString((numBuffer * Double.parseDouble(String operand)));
}
catch(NumberFormatException nfe)
{
result = "Number format exception";
}
return result;
}
public String divide(String operand)
{
String result = "";
try
{
result = Double.toString((numBuffer / Double.parseDouble(operand)) );//this is where the error with parenthesis begin
}
catch(NumberFormatException nfe)
{
result = "Number format exception";
}
return result;
    // Display result
    System.out.println(args[0] + ' ' + args[1] + ' ' + args[2]
      + " = " + result);
  }
}

The lines that read:

return result;

should be removed from your main method. The main method should just use that result variable rather than attempting to return it.

There are no try...catch blocks around that switch statement of yours considering that any parseXXX method is very much capable of throwing a NumberFormatException. Plus writing parseInt(xxx) or parseDouble(xxx) in every switch case seems kind of redundant.

Also a status code of '0' denotes success so your System.exit(0) should be System.exit(1);

A better way to do the entire thing would be:

package daniweb;

public class Tmp {

    public static void main(String args[]) {
        args = new String[]{"/", "s", "r"};
        if (args.length != 3) {
            System.out.println("Usage: java Calculator operand1 operator operand2");
            System.exit(1);
        }

        double result = 0.0;
        ComputationUnit unit = new ComputationUnit();
        unit.populateFromCommandLine(args);
        try {
            result = unit.compute();
            System.out.println(unit.getOp1() + " " + unit.getOperand() + " " + 
                    unit.getOp2() + " = " + result);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

class ComputationUnit {

    private double op1;
    private double op2;
    private char operand;

    public ComputationUnit() {
        super();
    }

    public ComputationUnit(char operand, double op1, double op2) {
        this.op1 = op1;
        this.op2 = op2;
        this.operand = operand;
    }

    public void populateFromCommandLine(String args[]) {
        try {
            operand = args[0].trim().charAt(0);
            op1 = Double.parseDouble(args[1]);
            op2 = Double.parseDouble(args[2]);
        } catch (NumberFormatException nfe) {
            System.out.println("Please enter a valid number: " + nfe.getMessage());
            System.exit(1);
        } catch (Exception e) {
            System.out.println("An error occured: " + e.getMessage());
            System.exit(1);
        }
    }

    public double compute() {
        switch (operand) {
            case '+':
                return (op1 + op2);
            case '-':
                return (op1 - op2);
            case '*':
                return (op1 * op2);
            case '/':
                return (op1 / op2);
            default:
                throw new IllegalArgumentException("Unknown operand: " + operand);
        }
    }

    public double getOp1() {
        return op1;
    }

    public double getOp2() {
        return op2;
    }

    public char getOperand() {
        return operand;
    }

    public void setOp1(double op1) {
        this.op1 = op1;
    }

    public void setOp2(double op2) {
        this.op2 = op2;
    }

    public void setOperand(char operand) {
        this.operand = operand;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.