0

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);
  }
}

Edited by Dani: Formatting fixed

4
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by ~s.o.s~
0

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.

0

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);
  }
}

Edited by Dani: Formatting fixed

0

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.

0

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;
    }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.