Exception... Calculator

I am practicing on some problems. I have attached the code FYI.

I don't want code solution rather some discussion and direction you may have for me. With Exception there are so many different way of handling errors I suppose. I want to discuss different approaches.

In the attached code user supplies (from prompt line):
6 + 3
6 -3
6 "*" 3
6 / 3

to get 9, 3, 24, and 2, respectively.

Possible pitfalls are:

1. If there are not exactly 3 parts (operand1, operator, and operand2) available.
                              (like 2 +, 2+4 where 2 + 4 is expected, 4 + 3 - 3, etc.)

2. agrs[0] and/or args[2] are not numeric.

3. operators are something other than +, -, *, or /

4. In the case of division, args[2] is non zero.

Possible solutions:

A. Write a separate exception class to implement in Calculator class.
B. Write a method for each of the four items (in the Calculator class) where each method checks on of the 4 items and throws an exception.
C. Write one method (in the Calculator class) to check each of the four items above to throw an exception.
    (not as good as B I guess)

D. Or, just add try/catch in the body of the existing Calculator class given below.

Please comment on each of the above methods. Any advantages or disadvantages. Please no links unless you have to.

Thank you.








public class Calculator {
    
    public static void main(String[] args) {
        
        DecimalFormat df=new DecimalFormat("0.##");
        
        if (args.length !=3) {
            System.out.println(
                    "Usage: java Calculator operand1 operator operand2\n");
            
            System.exit(0);
        }
        
        double result=0;
        
        switch (args[1].charAt(0)){
            case '+': result=Double.parseDouble(args[0]) +
                             Double.parseDouble(args[2]);
                      break;
            case '-': result=Double.parseDouble(args[0]) -
                             Double.parseDouble(args[2]);
                      break;
            case '*': result=Double.parseDouble(args[0])*
                             Double.parseDouble(args[2]);
                      break;
            case '/': result=Double.parseDouble(args[0]) /
                             Double.parseDouble(args[2]);
        }
        
        System.out.print(df.format(Double.parseDouble(args[0]))+' '+ 
                                                     (args[1])+' '+
                         df.format(Double.parseDouble(args[2]))+" = "+
                         result+"\n"); 
                          
    }
}

Open in new window

LVL 34
Mike EghtebasDatabase and Application DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

for_yanCommented:

You want to throw exception rather than deal with therror and write a message
in case your method is supposed to be used by ither people fior calling in theier
programs (or by youerslef form diffferent classes) then exception will help you in a sens that you can defere
handling the stuation oto the calling calss/method
If you are writing this methiod for this particular application I'd
rather not throw exceptions
0
themrrobertCommented:
Probably use strtok() to separate the strings by spaces and or the operators.
http://www.cplusplus.com/reference/clibrary/cstring/strtok/

Then you can iterate through the array knowing the 3 parts are good, and you can count the number of elements to make sure you have the appropraite # of parts before calculating/

Another way to go would be regex, but this is far more complicated and slower
0
for_yanCommented:
My preference would rathe nbe to write one method vaklidateInput() in the very beginning
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

for_yanCommented:
You would call validateInput it in the very beginning send args[] as aparameter
and then go through all those cases you outlined
and make up the error mesage appropriate for each case
0
for_yanCommented:
I would even make message "concatenable" as you go through all casees of checking - you concatenate
error message. And then I'd return String from that method back to your
calling code
and then I'd check if this is just empty string "" - then you go forward and find and print result
Otherwise - you just printe this error message
0
for_yanCommented:
I would do something like that:
(I use your previous code and do not write out the particular conditions -
this just shows the general scheme of things):

public class Calculator {

    public static String validateInput(String [] ss){
        String message = "";
       //       if(...){
       //            message += " No oprator in the second postion;";
        //      }
          //       if(...){
       //            message += " Too many operands";
        //      }
        
        
        
        return message;
    }
    public static void main(String[] args) {
        
        String sMessage = validateInput(args);
        
        if(sMessage.trim().length() != 0){
            
            System.out.println(" error in input : " + sMessage);
            System.out.println(
                    "Usage: java Calculator operand1 operator operand2\n");
            
            
        }

        for(String s: args){
            System.out.println(s);
        }

        if (args.length !=3) {
            System.out.println(
                    "Usage: java Calculator operand1 operator operand2\n");

            System.exit(0);
        }


        int result=0;

        if(args[1].equals("\\\\*"))args[1]= "*";
        System.out.println(args[1].charAt(0));

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

        System.out.print(args[0]+' '+ args[1]+' '+args[2]
                +" = "+result+"\n");
    }
}

Open in new window

0
for_yanCommented:
I think the actual checking iof conditions is mostly obvious - you can chcek the
array.length, chec the value of eleement with index 1 for operator

When you need to check for numeric or int value
you can do it like that

String sNum = "abc";

boolean goodNumber = true;

try{

new Double(sNum);
}
catch (Exception ex){
goodNumber = false;

}

if(!goodNumber) //error

Of course if you need int, then
you should
do
new Integer(...)
inside this tiny try catch loop

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
for_yanCommented:
Of course first you check more general conditions
and of they are not satisfied return your error meassaeg immedaitely without goiing to more
special

So if you have not three arguments - you don't want to check for anything else

if you have three arguments but seciond is not a +,-/*
you don't want to check for operands

and in the last thing  if your operand is division check for args[2] not to be zero
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.