# 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");

}
}
``````
Java

Last Comment
for_yan
for_yan

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
themrrobert

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
for_yan

My preference would rathe nbe to write one method vaklidateInput() in the very beginning
for_yan

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
for_yan

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
for_yan

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");
}
}
``````
for_yan

THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
for_yan

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
Java

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

102K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts

TRUSTED BY